final keyword
The emergence of inheritance improves the reusability of code and facilitates development. However, there are also problems. Some classes do not want to be inherited after description, or some method functions in some classes are fixed and do not want subclasses to be overridden. However, when subclasses inherit these special classes, they can override their methods. How to solve it?
To solve these problems, you need to use a keyword final, which means final and immutable. Final is a modifier that can be used to modify classes, class members, and local variables.
Features of final
final decorated classes cannot be inherited, but they can inherit other classes.
class Yy {} final class Fu extends Yy{} //You can inherit Yy class class Zi extends Fu{} //Fu class cannot be inherited final Modification methods cannot be overridden,But the parent class is not final Modifier method, which can be added after subclass coverage final.
The method modified by final represents the final method. Subclasses cannot be overridden and can be inherited for use
class Fu { // The method modified by final cannot be overwritten, but can be inherited and used public final void method1(){} public void method2(){} } class Zi extends Fu { //Override method2 method public final void method2(){} }
final modified variable: it is equivalent to a constant. After compiling the production. class file, the variable becomes a constant value
final Modified variables are called constants, and these variables can only be assigned once. final int i = 20; i = 30; //An error is reported in the assignment. The variable modified by final can only be assigned once The variable value of reference type is the object address value. The address value cannot be changed, but the object attribute value in the address can be modified. final Person p = new Person(); Person p2 = new Person(); p = p2; //The recorded address value of the variable p modified by final cannot be changed p.name = "Xiao Ming";//You can change the value of the name attribute in the p object //p cannot be another object, and the value of the name or age attribute in the p object can be changed. Modify the member variable and assign a value before creating the object, otherwise an error will be reported.(When there is no explicit assignment, multiple constructors need to assign values to them.)
class Demo { //Direct assignment final int m = 100; //The member variable modified by final needs to be assigned before creating the object, otherwise an error will be reported. final int n; public Demo(){ //You can assign a value to the variable n in the construction method called when creating the object n = 2016; } }
static keyword
When defining a class, the class will have corresponding properties and methods. Properties and methods are called by creating this class object. When a method of an object is called and the method does not access the unique data of the object, it is redundant for the method to create the object.
But if we don't create an object, the method can't be called. At this time, we will think, can we call a method without creating an object? Yes, we can implement it through the static keyword. Static is a static modifier, which is generally used to modify members in a class.
static features
The member variable modified by static belongs to a class and does not belong to an object of this class. (that is, when multiple objects access or modify static modified member variables, one object modifies the static member variable value, and the static member variable value in other objects changes accordingly, that is, multiple objects share the same static member variable.)
class Demo { public static int num = 100; } class Test { public static void main(String[] args) { Demo d1 = new Demo(); Demo d2 = new Demo(); d1.num = 200; System.out.println(d1.num); //The result is 200 System.out.println(d2.num); //The result is 200 } }
Members modified by static can and are recommended to be accessed directly through the class name. Format for accessing static members:
- Class name. Static member variable name
- Class name. Static member method name (parameter)
- Object name. Static member variable name ------ This method is not recommended and a warning will appear
- Object name. Static member method name (parameter) ---- this method is not recommended and a warning will appear
class Demo { //Static member variable public static int num = 100; //Static method public static void method(){ System.out.println("Static method"); } } class Test { public static void main(String[] args) { System.out.println(Demo.num); Demo.method(); } }
static considerations
Static content takes precedence over object existence. You can only access static content and cannot use this/super. The content of static decoration is stored in the static area.
class Demo { //Member variable public int num = 100; //Static method public static void method(){ //this.num; this/super cannot be used. System.out.println(this.num); } }
Static members can only access static members in the same class.
class Demo { //Member variable public int num = 100; //Static member variable public static int count = 200; //Static method public static void method(){ //System.out.println(num); In static methods, only static member variables or static member methods can be accessed System.out.println(count); } }
The main method is a static method. It is only an entry for program execution. It does not belong to any object and can be defined in any class.
Define static constants
During development, we want to define a static constant in the class. We usually use the variable modified by public static final to complete the definition. At this time, variable names are capitalized, and multiple words are connected with underscores.
Definition format: public static final data type variable name = value;
class Company { public static final String COMPANY_NAME = "Baidu"; public static void method(){ System.out.println("A static method"); } }
When we want to use the static members of a class, we don't need to create an object. We can directly use the class name to access it.
System.out.println(Company.COMPANY_NAME); //Print Baidu Company.method(); // Call a static method
be careful:
- Each member variable in the interface is decorated with public static final by default.
- The member variables in all interfaces are static constants. Since the interface has no constructor, the assignment must be displayed. It can be accessed directly with the interface name.
interface Inter { public static final int COUNT = 100; } //Static variables in the provider Inter.COUNT
Anonymous object
Anonymous object means that when creating an object, there are only statements to create the object, but the object address value is not assigned to a variable.
public class Person{ public void eat(){ System.out.println(); } } //Create a normal object Person p = new Person(); //Create an anonymous object new Person();
Characteristics of anonymous objects:
Create anonymous objects for direct use without variable names.
new Person().eat() //The eat method is called by an unnamed Person object.
Anonymous objects can only be used once without specifying their reference variables.
new Person().eat(); Create an anonymous object and call eat method new Person().eat(); Want to call again eat Method to recreate an anonymous object
Anonymous objects can be used as parameters received by methods and return values of methods
class Demo { public static Person getPerson(){ //Common way //Person p = new Person(); //return p; //Anonymous object as method return value return new Person(); } public static void method(Person p){} } class Test { public static void main(String[] args) { //Call the getPerson method to get a Person object Person person = Demo.getPerson(); //Call method method Demo.method(person); //Anonymous objects are parameters that are received as methods Demo.method(new Person()); } }
Inner class
When a class is written inside other classes, it can be written in the member position and local position of other classes. At this time, a class written inside other classes is called an internal class. Other classes are also called external classes.
When to use inner classes? When describing things, if a thing contains other things that may be included, for example, when describing a car, the car also contains the engine, then the engine can be described using an internal class.
class automobile { //External class class engine { //Inner class } }
Classification of internal classes
Internal classes are divided into member internal classes and local internal classes.
When defining an internal class, it is a normal process of defining a class, which also includes various modifiers, inheritance and implementation relationships, etc. All members of the external class can be accessed directly in the internal class.
Member inner class
Defines the member location in the external class. Similar to member variables in a class, they can be accessed through external class objects
Define format:
class External class { Modifier class Inner class { //Other codes } }
Access method: external class name. Internal class name variable name = new external class name (). New internal class name ();
class Body {//External class, body private boolean life = true; //Life state public class Heart { //Internal class, heart public void jump() { System.out.println("The heart thumped") System.out.println("Life state" + life); //Accessing external class member variables } } } //Accessing internal classes public static void main(String[] args) { //Create an internal class object Body.Heart bh = new Body().new Heart(); //Calling a method in an inner class bh.jump(); }
Local inner class
Defines a local location in an external class method. Similar to accessing a local variable in a method, it can be accessed by calling a method
Define format:
class External class { Modifier return value type method name(parameter) { class Inner class { //Other codes } } }
Access method: create an internal class object in the external class method for access
Local internal class code demonstration
//Define class class Party {//External class, Party public void puffBall() {// Balloon blowing method class Ball {// Inner class, balloon public void puff() { System.out.println("The balloon inflated"); } } //Create an internal class object and call the puff method new Ball().puff(); } } //Accessing internal classes public static void main(String[] args) { //Create an external class object Party p = new Party(); //Call the puffBall method in the external class p.puffBall(); }
Anonymous Inner Class
Inner classes are designed to cope with more complex inter class relationships. It will be involved in viewing the source code, which is difficult to encounter in daily business. I won't repeat it here. The most commonly used inner class is anonymous inner class, which is a kind of local inner class.
The anonymous inner class defined has two meanings:
- Temporarily defines a subclass of a specified type
- Create the object of the subclass just defined immediately after definition
Defines the role and format of anonymous inner classes
Function: anonymous inner class is a shortcut to create subclass objects of a certain type.
Format:
new Parent class or interface(){ //Method override };
Code demonstration:
//Existing parent class: public abstract class Person{ public abstract void eat(); } //Define and create the subclass object of the parent class, and assign it to the parent class reference variable in a polymorphic way Person p = new Person(){ public void eat() { System.out.println("I ate it. "); } }; //Call the eat method p.eat();
Using anonymous objects, the two steps of defining subclasses and creating subclass objects are completed in one format at a time. Although it is two steps, the two steps are completed together.
If an anonymous inner class does not define a variable reference, it is also an anonymous object. The code is as follows:
new Person(){ public void eat() { System.out.println("I ate it. "); } }.eat();
Code block
Local code block:
Local code blocks are defined in methods or statements.
characteristic:
- The code area delimited by "{}" only needs to pay attention to the different scopes at this time
- Methods and classes are bounded by code blocks
class Demo{ public static void main(String[] args) { { int x = 1; System.out.println("Common code block" + x); } int x = 99; System.out.println("Outside the code block" + x); } }
Construction code block:
A construction code block is a code block that defines the position of a member in a class
characteristic:
- Prior to the execution of the construction method, the construction code block is used to perform the initialization actions required by all objects
- The construction code block is executed once for each object created.
public class Person { private String name; private int age; //Construct code block { System.out.println("The construction code block is executed"); } Person(){ System.out.println("Person Parameterless constructor execution"); } Person(int age){ this.age = age; System.out.println("Person(age)Constructor execution of parameter"); } } class PersonDemo{ public static void main(String[] args) { Person p = new Person(); Person p1 = new Person(23); } }
Static code block:
Static code block is a code block defined at the member position and decorated with static.
characteristic:
It takes precedence over the main method execution, over the construction code block execution, and when the class is used for the first time in any form.
No matter how many objects are created by this class, the static code block is executed only once.
It can be used to assign values to static variables and initialize classes.
public class Person { private String name; private int age; //Static code block static{ System.out.println("Static code blocks are executed"); } }
Use details of different modifiers
Modifiers that modify classes, methods, and variables
- Public permission modifier, public access, class, method, member variable
- Protected permission modifier, protected access, method, member variable
- Write nothing by default is also a permission modifier, default access, class, method, member variable
- Private permission modifier, private access, method, member variable
- Static static modifier method, member variable
- final modifier, class, method, member variable, local variable
- Abstract abstract, abstract modifier, class, method
When we write programs, permission modifiers are generally placed before all modifiers, and different permission modifiers cannot be used at the same time;
- At the same time, abstract and private cannot be used at the same time;
- At the same time, abstract and static cannot be used at the same time;
- At the same time, abstract and final cannot be used at the same time.
Modifier of modifier class
Modifier classes can only use public, default, final and abstract keywords, and the most used is public keyword
public class Demo {} //The most common way class Demo2{} public final class Demo3{} public abstract class Demo4{}
Modifier that modifies a member variable
- Public: public
- Protected: protected
- : default
- Private: private
- final: final
- Static: static
private is the most used
public int count = 100; protected int count2 = 100; int count3 = 100; private int count4 = 100; //The most common way public final int count5 = 100; public static int count6 = 100;
Modifier that modifies the constructor
- Public: public
- Protected: protected
- : default
- Private: private
The most used is public
public Demo(){} //The most common way protected Demo(){} Demo(){} private Demo(){}
Modifiers that decorate member methods
- Public: public
- Protected: protected
- : default
- Private: private
- final: final
- Static: static
- abstract: abstract
The most used is public
Class, abstract class and interface as parameters and return values
- When class is used as a method parameter, it indicates the object of the class to be passed into the method
- When class is used as the return value of a method, it indicates that the method wants to return an object of this class.
- When an abstract class is used as a method parameter, it indicates that a subclass object that implements all abstract methods of the abstract class is to be passed in.
- When an abstract class is used as a method return value, it indicates that a subclass object that implements all abstract methods of the abstract class needs to be returned.
- When interface is used as a method parameter, it indicates that the method needs to pass in an interface implementation class object.
- When interface is used as the return value of a method, it indicates that the method needs to return an interface implementation class object.