JAVA_SE basics -- 42. final Modifier
Do not spray ~
The final keyword can be used to modify classes, variables, and methods. It has the meaning of "This cannot be changed" or "final, therefore, the classes, variables, and Methods Modified by final have the following features:
1. The final modified class cannot be inherited. Instance 1
2. The final modification method cannot be overwritten by the quilt class. Instance 2
3. fianl modified variables (member variables and local variables) are constants and can only be assigned once. Instance 3
4. When modifying a member variable, fianl must assign an initialization value while defining the variable. Instance 4
Instance 1
Final class A {// use the final keyword to modify class A} class B extends A {/B class to inherit class A} class Demo1 {public static void main (String [] args) {B B = new B (); // create a class B Instance Object }}
Running result:
Instance 2
Class A {// define class A public final void shout () {}// use the final keyword to modify shout () method} class B extends A {// class B inherits class A public void shout () {}// override shout () of class () method} class Demo1 {public static void main (String [] args) {B B B = new B (); // create B class instance object }}
Running result:
Instance 3
Class Demo1 {public static void main (String [] args) {final int x = 10; // you can assign the value x = 5 for the first time; // an error will be returned when you assign the value again }}
Running result:
Instance 4
Class A {// define A class final String name; // use the final keyword to modify the name attribute public void introduce () {// define the introduce () method and print nameSystem. out. println (name = + name) ;}} class Demo1 {public static void main (String [] args) {A a = new (); // create A class a instance object. introduce (); // call the introduce () method of Class }}
Running result:
If you assign values to member variables, no error is reported.
Class A {// define A class final String name = Jiang haihao; // use the final keyword to modify the name attribute public void introduce () {// define the introduce () method and print nameSystem. out. println (name = + name) ;}} class Demo1 {public static void main (String [] args) {A a = new (); // create A class a instance object. introduce (); // call the introduce () method of Class }}
Running result: