1 static
We sometimes hope that no matter whether objects are generated or how many objects are generated, there is only one copy of some specific data in the memory space. For example, all Chinese have a country name, and each Chinese shares the country name. It is not necessary to assign a variable representing the country name in each Chinese instance object
static can be used to decorate: attributes, methods, code blocks, internal classes
In Java, remember: static is not allowed to modify local variables.
Inside the static method, you can only access the static modified properties or methods of the class, but not the non static structure of the class.
• use static to modify attributes: static variables (or class variables)
• attributes are divided into static attributes vs non static attributes (instance variables) according to whether static modification is used
• instance variable: we have created multiple objects of the class, and each object independently has a set of non static attributes in the class. When modifying a non static property in one object, it will not result in the modification of the same property value in other objects.
• static variables: we have created multiple objects of the class, and multiple objects share the same static variable. When a static variable is modified through an object, it will cause other objects to call the static variable. It is modified.
• static variables are loaded as the class is loaded. It can be called by "class. Static variable"
• static variables are loaded before objects are created.
• since the class will only be loaded once, only one copy of the static variable will exist in memory: in the static field of the method area.
• use static modification method: static method
• it is loaded as the class is loaded, and can be called through "class. Static method"
• in static methods, only static methods or properties can be called
• in non static methods, you can call either non static methods or properties or static methods or properties
• static considerations:
• this keyword and super keyword cannot be used in static methods
• during development, how to determine whether an attribute should be declared as static?
• attributes can be shared by multiple objects and will not vary with different objects.
• constants in classes are also often declared as static
• during development, how to determine whether a method should be declared as static?
• methods for operating static attributes, usually set to static
• methods in tool classes are traditionally declared as static. For example: Math, Arrays, Collections
example
public class Order { //static executes when it is loaded, so it is better than the constructor static int num = 0; String name = "qqqqqq"; static String name2 = "wwwwwwwwwww"; //This calling function is executed once. When calling, go to the class to find the constructor static Order parentClass = new Order(); Order(){ System.out.println("Here is the constructor*************"); } { System.out.println("name1:" + name); System.out.println("Here is block 1============"); } static { num += 1; System.out.println("parentClass.name:"+parentClass.name); System.out.println("This is a static block*************" + num); } public static void main(String[] args) { // There is a problem with the execution order of the constructor. / / calling directly during construction takes up Static parentClass, and static cannot be called Order pa = new Order(); }
We can see that the static code block is called only once. You can think about whether this code block is called by pa or parentClass. When pa is constructed, the direct call occupies the Static parentClass and cannot call static. That is, when the code goes to Order pa = new Order(), the static block, block 1 and constructor have been called once, Only because static Order parentClass = new Order() is in Order, it is output first.
Call order: static > code block > constructor
2 main
The main method is used as the entry of the program
When the JVM runs the program, it will first look for the main method. Among them, public is the permission modifier, indicating that any class or object can access this method, and static indicates that the main method is a static method, that is, the code in the method is stored in the static storage area. As long as the class is loaded, you can use this method without instantiating the object, and you can access it directly through the class name main() is accessed directly. When the JVM starts, it finds the entry address of the method according to the signature of the above method (it must be decorated with public and static, the return value is void, and the method parameter is a string array). If it can be found, it will execute. If it cannot be found, an error will be reported. Void indicates that the method has no return value. Main is the special method name recognized by the JVM and the entry method of the program. The string array parameter args provides a means for developers to interact with programs in the command-line state.
A main method can be named in each class, and an entry can be specified when the program is executed
public class MainTest { public static void main(String[] args) {//entrance Main.main(new String[100]); MainTest test = new MainTest(); test.show(); } public void show(){ } } class Main{ public static void main(String[] args) { for(int i = 0;i < args.length;i++){ args[i] = "args_" + i; System.out.println(args[i]); } } }
The formal parameters in the main method can also be used as a way to interact with the console
package test14; public class Main { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } } }
Operate on the console
Interview questions
Here, the file of Something class is called otherthing java
class Something {
public static void main(String[] something_to_do) {
System.out.println("Do something ...");
} }
Can the above program be compiled and run normally?
Compileable
Operable
3 code block
If a code block in a class has modifiers, it can only be modified by static, which is called static block. If static modification is not used, it is a non static code block.
Static code block
• there can be output statements.
• you can initialize class attributes and class declarations.
• non static attributes cannot be initialized. That is, non static properties and methods cannot be called.
• if there are multiple static code blocks, they are executed from top to bottom.
• static code blocks are executed before non static code blocks.
• static code blocks are loaded as the class is loaded and executed only once.
Non static code block
• there can be output statements.
• you can initialize class attributes and class declarations.
• in addition to calling non static structures, you can also call static variables or methods.
• if there are multiple non static code blocks, they are executed from top to bottom.
• it is executed every time an object is created. And executed before the constructor.
for example
package test14;public class Main { public static void main(String[] args) { System.out.println("total = " + Person.total); System.out.println("total = " + Person.total); } } class Person { public static int total; static { total = 100; System.out.println("in static block!"); } }
This is how the debug looks. You can see that when the first output statement is executed, the code block is executed, and then output
in static block!
total = 100
This is because of person Static code block is executed during total, and in static block! Is output first!, Then call the value of total.
3 final
When declaring classes, variables and methods in Java, you can use the keyword final to modify them, indicating "final"
• classes marked final cannot be inherited.
• methods marked final cannot be overridden by subclasses.
• final ly marked variables (member variables or local variables) are called constants. The name is capitalized and can only be assigned once
• the member variables of the final tag must be explicitly assigned in the declaration or in each constructor or code block before they can be used.
• final double MY_PI = 3.14;
Error message:
The last local variable x cannot be assigned. It must be empty and cannot use compound assignment
4 abstract classes and abstract methods
With the definition of new subclasses in the inheritance hierarchy, the class becomes more and more specific, while the parent class is more general and general. Class design should ensure that parent and child classes can share features. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class
Java allows class designers to specify that a superclass declares a method but does not provide an implementation, and the implementation of the method is provided by a subclass. Such methods are called abstract methods. A class with one or more abstract methods is called an abstract class.
• use the abstract keyword to modify a class, which is called an abstract class.
• use abstract to modify a method, which is called abstract method.
• abstract methods: there are only method declarations, but no method implementations. End with semicolon:
For example: public abstract void talk();
• classes containing abstract methods must be declared as abstract classes.
• abstract classes cannot be instantiated. Abstract classes are used to be inherited. Subclasses of abstract classes must override the abstract methods of the parent class and provide method bodies. If you do not override all the abstract methods, it is still an abstract class.
• variables, code blocks and constructors cannot be modified with abstract;
• abstract cannot be used to modify private methods, static methods, final methods and final classes.
As we all know, the parent class extracts the attributes and methods jointly owned by the child classes. Some of these attributes and methods have been explicitly implemented, and some cannot be determined. Then we can define them as abstractions and reuse them in the future. In this way, abstract classes are born.
Abstract classes are used to extract the same but uncertain things for future reuse. The purpose of defining an abstract class is to implement an abstract class in a subclass.
public abstract class Role {//An abstract class private String name; private int age; private String sex; public Role(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } public Role() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } abstract void play() ;//An abstract method @Override public String toString() { return "Role [name=" + name + ", age=" + age + ", sex=" + sex + "]"; } } public class Employee extends Role { private int salary;//salary static int ID; public Employee(String name, int age, String sex, int salary) { super(name, age, sex); this.salary = salary; } public Employee(String name, int age, String sex) { super(name, age, sex); } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public static int getID() { return ID; } public static void setID(int iD) { ID = iD; } public void play() {//Implement abstract methods System.out.println("Playing"); } final public void sing() { System.out.println("I'm singing!!"); } public Employee(int salary) { super(); this.salary = salary; System.out.println("super"); } @Override public String toString() { return "Employee [salary=" + salary + "]"; } }
5 interface
Sometimes you must derive a subclass from several classes and inherit all their properties and methods. However, Java does not support multiple inheritance. With an interface, you can get the effect of multiple inheritance.
General constant values and abstract methods are defined in the interface
Characteristics of interface
• defined by interface.
• all member variables in the interface are modified by public static final by default.
• all abstract methods in the interface are modified by public abstract by default.
• there is no constructor in the interface.
• the interface adopts multi inheritance mechanism.
explain:
• define the syntax format of Java classes: write extensions first and then implements
class SubClass extends SuperClass implements InterfaceA{ }
• a class can implement multiple interfaces, and interfaces can also inherit other interfaces.
• the class implementing the interface must provide the specific implementation contents of all methods in the interface before instantiation. Otherwise, it is still an abstract class.
• the main purpose of the interface is to be implemented by the implemented class. (interface oriented programming)
• similar to inheritance, there is polymorphism between interfaces and implementation classes
• interface and class are parallel, or can be understood as a special class. In essence, an interface is a special abstract class. This abstract class only contains the definitions of constants and methods (JDK7.0 and before), without the implementation of variables and methods.
The difference between abstract classes and interfaces
public class USBTest { public static void main(String[] args) { Computer com = new Computer(); //1. Create a non anonymous object of the non anonymous implementation class of the interface Flash flash = new Flash(); com.transferData(flash); //2. Create the anonymous object of the non anonymous implementation class of the interface com.transferData(new Printer()); //3. Create a non anonymous object of the anonymous implementation class of the interface USB phone = new USB(){ @Override public void start() { System.out.println("The phone starts working"); } @Override public void stop() { System.out.println("End of mobile phone work"); } }; com.transferData(phone); //4. Create the anonymous object of the anonymous implementation class of the interface com.transferData(new USB(){ @Override public void start() { System.out.println("mp3 start-up"); } @Override public void stop() { System.out.println("mp3 power cut-off"); } }); } } class Computer{ public void transferData(USB usb){//USB usb = new Flash(); usb.start(); System.out.println("Details of specific transmission data"); usb.stop(); } } interface USB{ //Constant: defines the length, width, maximum and minimum transmission speed, etc void start(); void stop(); } class Flash implements USB{ @Override public void start() { System.out.println("U Disc opening operation"); } @Override public void stop() { System.out.println("U Disk end work"); } } class Printer implements USB{ @Override public void start() { System.out.println("Printer on"); } @Override public void stop() { System.out.println("Printer finished working"); } }
If a default method is defined in an interface and a non abstract method with the same name and parameters is also defined in the parent class, there will be no conflict. Because the principle of class priority is followed at this time. Default methods with the same name and parameters in the interface are ignored.
Improvement in jdk8
In Java 8, you can add static methods and default methods for interfaces. From a technical point of view, this is completely legal, but it seems to violate the concept of interface as an abstract definition.
• static method: use static keyword to modify. You can call static methods directly through the interface and execute their method bodies. We often use static methods in classes that work with each other. You can find paired interfaces and classes such as Collection/Collections or Path/Paths in the standard library.
• default method: the default method is decorated with the default keyword. Can be called by implementing class objects. We provide new methods in the existing interfaces while maintaining compatibility with the old version of the code. For example, the java 8 API provides rich default methods for interfaces such as Collection, List and Comparator
6 internal class
Defining a class in another given class or method is called an inner class.
Member inner class
• members in non static member inner classes cannot be declared static. Static members can only be declared in external classes or static member inner classes.
• the external class accesses the members of the internal class by means of "internal class. Member" or "internal class object. Member"
• the inner class of a member can directly use all members of the outer class, including private data
• when you want to use an inner class in the static member part of an outer class, consider declaring the inner class static
How to call internal or external members
package test14; import test14.Outer.inOuter; public class Outer {//External class private int i =1; String s ="External class"; public class inOuter{//Inner class String s="Inner class"; void test(){ System.out.println(Outer.this.s); System.out.println(i); System.out.println(s); } } public static void main(String[] args) { Outer o =new Outer();//Create external objects inOuter i = o.new inOuter();//External objects creating internal objects i.test(); } }
When an inner and outer class has a member variable or method with the same name, use outer this. s. Use this keyword to call.
Static inner class
Static inner classes cannot directly access non static members of external classes, but they can be accessed through new external class () members;
public class Outer {//External class private int i =1;// String s ="External class"; public static class inOuter{//Inner class // String s = "internal class"; void test(){ System.out.println(new Outer().s); // System.out.println(i); // System.out.println(s); } } public static void main(String[] args) { Outer o =new Outer(); inOuter i = new inOuter();//Notice the change here i.test(); }
It can also be called in this way when the external is static and the internal is static and has the same name.
Method inner class
The method inner class is defined in the method of the outer class, and the method inner class can only be used in the method;
class O {// External class private int i = 1;// static String s = "External class"; void test(){//Method inner class System.out.println("Method inner class"); class inOuter {// Inner class String s = "Inner class"; void test() { System.out.println("Call method inner class"); } } // inOuter i =new inOuter(); // Only here can the inner class of the method be called. // i.test(); } } public class Outer{ public static void main(String[] args) { O o = new O(); o.test(); } }
Before annotation
After uncomment
Anonymous Inner Class
Anonymous inner classes cannot define any static members, methods and classes. Only one instance of anonymous inner classes can be created. An anonymous inner class must be behind new, which implicitly implements an interface or class.
The so-called anonymous inner class is an inner class without an explicit name. In actual development, this kind of inner class is used very much.
Format:
• new parent class constructor (argument list) | implementation interface (){
• / / class body part of anonymous inner class
• }
Characteristics of anonymous inner classes
• anonymous inner classes must inherit the parent class or implement interfaces
• an anonymous inner class can only have one object
• anonymous inner class objects can only be referenced in polymorphic form
public class Outernm { public void method() { new Inner() { @Override public void info() { System.out.println("Anonymous Inner Class "); } }.info(); //Pay attention to the operation here } public static void main(String[] args) { Outernm o =new Outernm(); o.method(); } } interface Inner { public void info(); }