this keyword (2)
this review
Observation Code
public class Dog { String sn; String name; int age; public Dog(){} public Dog(String s,String n,int a){ sn = s; name = n; age = a; } public void sayHi(){ System.out.println("My name:"+ name); System.out.println("My age:" + age); } }
What is the problem with the above code?
Where does this come from? What is this?
this mainly exists in two locations:
In constructor: represents the object currently created
In method: This indicates which object calls the method of this
After optimization:
/** * Dog satisfying encapsulation concept */ public class Dog { private String sn; private String name; private int age; public void setSn(String sn) { this.sn = sn; } public String getSn() { return sn; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public Dog(String sn, String name, int age) { this.sn = sn; this.name = name; this.age = age; } public Dog() {} }
this memory map
this keyword indicates the current object itself. It is generally used inside a class. There is an address inside it that points to the currently initialized object itself.
public class Test01 { public static void main(String[] args) { Dog dog = new Dog(" Wangcai ", 20); System.out.println("dog = " + dog); } }
When new an object, two references are actually generated, one is the this keyword for calling its member variables and member methods inside the class dog, and the other is the dog for external programs to call instance members.
Three uses of this
(1) Call member variable
To solve the ambiguity between local variables and member variables, you must use
Call other instance methods
Intermodulation between non static methods in the same class (this can be omitted, but it is not recommended)
public void sayHi(){ // System.out.println("Hello, my name is" + this.name + ", and I am" + this.age + "years old"); System.out.println("My confession:"); this.showInfo(); }
(3) Call other constructor methods of this class
This can call other construction methods of this class, including syntax
this(); this(,,,);
Note: calling other construction methods of this class in the construction method must be written to the first sentence of the construction method, otherwise compile errors will occur.
A combination of this to meet the encapsulated Dog class in practice.
/** * Dog satisfying encapsulation concept */ public class Dog { private String sn; private String name; private int age; public void setSn(String sn) { this.sn = sn; } public String getSn() { return sn; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public Dog(String sn, String name, int age) { //this.sn = sn; // this.name = name; this(sn,name); this.age = age; } public Dog(String sn,String name){ this.sn = sn; this.name = name; } public Dog() {} public void sayHi(){ // System.out.println("Hello, my name is" + this.name + ", and I am" + this.age + "years old"); this.showInfo(); } public void showInfo(){ System.out.println("My confession:"); System.out.println("My name:" + this.name); System.out.println("My age:" + this.age); } }
super keyword (2)
Review super
Review when you used super:
In subclass methods, calling the method that the parent class is overlaid must use super.
super keyword
Super keyword indicates the parent class object. When a subclass wants to access the members of the parent class, it can use super.
super is just a keyword without internal reference (address).
super accesses non private fields of the parent class
System.out.println("My name" + super.nick); System.out.println("My health value" + super.health); System.out.println("My intimacy" + super.love); System.out.println("I am a" + this.strain);
super accesses non private methods of the parent class
super.print(); System.out.println("I am a" + this.strain);
super access parent class constructor
Syntax: super(); super(,,,);
example:
public class Dog extends Pet { String strain; public Dog(String nick,int health,int love,String strain){ super(nick,health,love); this.strain = strain; } ,,,, }
Summary:
The super call constructor must be written in the first sentence of the subclass constructor;
If the subclass constructor does not explicitly call the parent constructor, the jvm will call the parameterless constructor super() of the parent by default.
static modifier
How many cars does a factory produce?
=>The class that constitutes a Car counts how many objects are created by the Car?
=>Then continue to think: do you need a variable totalCount to count the number of objects created by Car?
=>Then continue to think: where to declare the variable totalCount?
static
Static keyword indicates static. You can modify variables to form static variables and modify methods to form static methods. Static variables and static methods are classified as static members of a class, which are decorated with the static keyword.
Static variable
In a class, a member variable modified with the static keyword is called a static variable, which is also called a class variable. All instances / objects of the class can be accessed and shared by all instances or objects of the class.
Syntax:
static Data type member variable [=Initial value];
Access to static variables
Class name.Static variable(Recommended writing) object/example.Static variable
How many cars has Car created?
public class Car{ String brand; String type; float price; // Static variables, categorizing all static int count = 0; public Car(){ //Car.count++; this.count++; } public Car(String brand,String type,float price){ this.brand = brand; this.type = type; this.price = price; // Car.count++; this.count++; } ,,,, }
Class variables / static variables are shared by all instances or objects of the class
Static method
Static can also modify methods, called static methods, which are classified as all, also known as class methods.
grammar
[Modifier ] static Return value type method name(parameter list ){ }
Static method access mode
Class name.Static method() object.Static method()
Static method properties
Static methods can access static variables and other static methods of classes
Static members (static variables and static methods) can be accessed in the instance method; Static methods cannot access instance members
public class Car { static int num = 0; public Car(){ Car.num++; //num++; <==> this.num++; //this.num++; } public static void test(){ System.out.println("test"); } public static int getNum(){ // System.out.println(this.count); // this.showInfo(); Car.test(); return Car.num; } public void showInfo(){ // Accessing static variables // System.out.println(Car.num); // Accessing static methods Car.getNum(); } }
The process by which the jvm loads static members
When loading a class into the static area of the jvm, the jvm will first scan the static members in xx.class, allocate space and initialize.
When you create an object through xx.class new, you can access the static member in the instance method of the object; Conversely, instance members cannot be accessed in static methods.
final modifier
Final represents the final meaning and can modify classes, methods, local variables and member variables.
Final class
The final modifier class represents the final class.
public final class Car extends MotoVehicle { }
The final class cannot be inherited.
Final method
If a method is modified by final, it is called the final method.
public final void test() { System.out.println("test"); }
The final method cannot be overridden.
constant
The local variable modified by final is called a constant. A constant can only be assigned once and cannot be re assigned.
Basic data type: the value represented cannot be changed
Reference data type: the referenced address value cannot be changed
(1)final modifies the basic data type
final int a = 10; // error // a = 20
(2)final modifier refers to the data type
// Often cited // final modifier refers to the data type final Car car = new Car(); System.out.println(car); car.setBrand("Benz"); car.setType("X5"); car.setBrand("Audi"); car.setBrand("A4"); // car is decorated with final and can no longer be used to point to other heap spaces //car = new Car(); //System.out.println(car);
Code block
The code marked by {} is called code block, which can be divided into ordinary code block, construction code block, static code block and synchronous code block according to its location.
Common code block
The common code block {} generally exists in the method to form the scope.
Scope properties:
Scopes can be nested, and inner scopes can access variables of outer scopes
When accessing a variable, first search the scope where the variable is located. If it can be found, stop searching and output the variable content; When this scope is not found, try to find the previous scope, and so on. The search chain formed by this process is called scope chain.
public class Dog { String nick; int health; int love; String strain; int count0 = 0; public void showInfo(){ int count1 = 10; // Common code block { // int count1 = 100; int count2 = 20; System.out.println(count2); System.out.println(count1); // System.out.println(count0); System.out.println(this.count0); } } ,,, }
Construct code block
The construction code block is in the class (inside the class) and outside the method.
Construct a code block to construct an object and execute it once before constructing a method.
public class Car{ private String brand; private String type; private float price; // Construct code block { System.out.println("Construct code block..."); } public Car(){} public Car(String brand,String type,float price{ System.out.println("Car(String,String,float)"); this.brand = brand; this.type = type; this.price = price; } }
If necessary, it is used when loading some resources (reading configuration files, xml files, etc.) before the execution of the construction method. We can put all operations before constructing the object into the construction code block.
Static code block
A code block modified by the static keyword is called a static code block. Static code blocks are located inside the class and outside the method.
Static code blocks are executed only once, before constructing code blocks and methods.
When the bytecode of a class is loaded into memory, the program needs to load some resources (read resource files, etc.), and static code blocks can be used. At this time, the loaded resources can generally be shared by multiple instances.
Inner class
public class Car{ String brand; String type; float price; static int count; // Static code block static{ System.out.println("Static code block..."); count = 0; } // Construct code block { System.out.println("Construct code block..."); } public Car(){} public Car(String brand,String type,float price){ System.out.println("Car(String,String,float)"); this.brand = brand; this.type = type; this.price = price; } }
How classes are organized
(1) Parallel relationship between classes
A file can define multiple classes, but only one public class can exist, and the name of the file is consistent with that of the public class.
public class Dog { } class Penguin{ }
After compilation
Dog has the same status as Penguin, and is defined as two files separately.
(2) Inclusion relationships between classes
public class Outer { public class Inner{ } }
After compilation
Outer and Inner are containment relationships. Outer is called an external class and Inner is called an internal class.
The Inner class exists as a member of Outer.
Internal class overview
What is an inner class? Define a class inside another class, call the inner class the inner class, and call the outer class the outer class.
Internal classes can be regarded as members of external classes like fields and methods, and members can be decorated with static.
Static inner class: the inner class decorated with static. If you access the inner class, you can access it directly with the outer class name
Instance (member) internal class: an internal class without static modification. The internal class is accessed by the object of the external class
Local (method) inner class: an inner class defined in a method, which is generally not used
Anonymous inner class: a special local inner class, which is suitable for classes used only once
For each internal class, the Java compiler generates a separate. Class file.
Static and instance internal classes: external class name $internal class name
Local internal class: external class name $numeric internal class name
Anonymous inner class: outer class name $number
Member inner class
The Inner class exists as a member of the outer class. The Inner class is called the member Inner class.
public class Outer { [Modifier ] class Inner{ } }
Generally speaking, the access modifier of the internal class of a member is the default access permission (package access permission). During development, you can add specific access permissions as needed.
Create member inner class object
public class Test01 { public static void main(String[] args) { // [1] Create an external class object Outer outer = new Outer(); // [2] Create an internal class object Outer.Inner inner = outer.new Inner(); inner.showInfo(); } }
Member inner class attribute
Member inner classes can directly access private members of outer classes
public class Outer { private String name = "Outer"; class Inner{ public void showInfo() { System.out.println("inner:showInfo()"); // [1] Access the private member System.out.println(name) of the external class; } } }
Static inner class
If a member inner class is statically modified into a static inner class, it exists as a static member of the outer class.
public class Outer { static class Inner{ } }
Create a static inner class object
public class Test01 { public static void main(String[] args) { // 1. Create static internal class object Outer.Inner inner = new Outer.Inner(); inner.showInfo(); } }
Static inner class properties
Static inner classes can access static private members of external classes
public class Outer { private static String name = "Outer"; static class Inner{ public void showInfo() { System.out.println("static inner:showInfo()"); System.out.println(name); } } }
Method inner class
When a class exists in a method, it constitutes the inner class of the method. Method internal classes can only exist in methods, and objects can only be created in methods,
There is no modifier before the inner class of the method, because the inner class is defined in the method and exists locally.
Method internal class properties
Method internal classes can read local variables of the method, but cannot modify them.
public class Outer { public void print(int count) { int a = 10; class Inner{ public void showInfo() { System.out.println("print():showInfo()"); // System.out.println(a); // System.out.println(count); // Local variables in a method can only be read and cannot be modified by internal classes of the method // count = 1000; } } // As long as a or count is accessed in showInfo, a and count are decorated with final, which cannot be used inside the method or outside the class a = 20; count = 1000; // Create method internal class object //Inner inner = new Inner(); //inner.showInfo(); // Anonymous object new Inner().showInfo(); } }
Anonymous Inner Class
When a class is used only once, it can be declared as an anonymous inner class. An anonymous inner class must have an implementation.
public class Outer { public void print(){ /* class Inner implements AInterface{ @Override public void showInfo() { System.out.println("inner.showInfo"); } } new Inner().showInfo(); */ /*AInterface aInterface = new AInterface(){ @Override public void showInfo() { System.out.println("inner.showInfo"); } }; aInterface.showInfo();*/ // Creating anonymous objects from anonymous classes new AInterface(){ @Override public void showInfo() { System.out.println("inner.showInfo"); } } }
Enumeration class
The birth history of enumeration
In the garment industry, the classification of clothes can be expressed as three situations according to gender: Men's clothing, women's clothing and neutral clothing.
private ? type; public void setType(? type){ this.type = type }
Define a variable to represent the classification of clothing? What is the type of this variable?
Use int and String types, and first assume that int types are used, because the classification is fixed. In order to prevent the caller from creating types indiscriminately, you can use constants to represent the three cases.
public class ClothType { public static final int MEN = 0; public static final int WOMEN = 1; public static final int NEUTRAL = 2; }
be careful:
Constants are decorated with final and are composed of uppercase letters. If they are composed of multiple words, they are separated by underscores.
At this point, the value passed by calling the setType method should be one of the three constants in the ClothType class. But there is still a problem
——You can still randomly pass in parameters, such as 100, which is unreasonable at this time.
Similarly, if you use String type, you can set data randomly. Then, it indicates that using int or String is type unsafe. So what if you use objects to represent three cases?
public class ClothType { public static final ClothType MEN = new ClothType(); public static final ClothType WOMEN = new ClothType(); public static final ClothType NEUTRAL = new ClothType(); }
At this time, calling setType can only pass in objects of closetype type, but it is still unsafe. Why? Because the caller can create a closetype object by himself, such as setType (New closetype()).
At this time, in order to prevent the caller from creating new objects without permission, we privatize the constructor of clothtype, which can not be accessed by the outside world. At this time, calling setType method can only pass in three constants in the clothtype class. The code becomes:
public class ClothType { public static final ClothType MEN = new ClothType(); public static final ClothType WOMEN = new ClothType(); public static final ClothType NEUTRAL = new ClothType(); private ClothType() {} }
High, really high! The code is a little complicated. If there is a syntax to define this type safe class with a fixed number of objects, it would be better to be simpler - Enumeration classes.
Definition and use of enumeration classes
Enumeration is a kind of special class. A fixed class can only have objects. The definition format is as follows:
public enum Enumeration class name{ const object A, const object B, const object C; }
Our custom enumeration classes directly inherit the java.lang.Enum class at the bottom.
public enum ClothType { MEN, WOMEN, NEUTRAL; }
Enumeration is a global public static constant, which can be called directly using the enumeration class name.
ClothType type = ClothType.MEN;
Because java.lang.Enum class is the parent class of all Enum classes, all Enum objects can call methods in Enum class
String name = enumerable object .name(); // Returns the constant name of an enumerated object int ordinal = enumerable object .ordinal(); // Returns the sequence number of enumerated objects, starting from 0
int ordinal = enumeration object. ordinal()// Returns the sequence number of enumerated objects, starting from 0
Note: enumeration classes cannot use to create objects
public class EnumDemo { public static void main(String[] args) { int ordinal = ClothType.MEN.ordinal(); String name = ClothType.MEN.name(); System.out.println(ordinal); System.out.println(name); new ClothType(); //Syntax error } }
That's all for day 10 of getting started with Java.
Data document address: Zero basics of Java development: day10 object oriented (IV). pdf
Related articles: Zero basics of Java development: day06 object oriented (I)