JavaSE - day7 code blocks, inheritance, final keyword, polymorphism

code block

   The concept of code blocks:

        Code enclosed in {} is a code block. {} is his scope, and the methods and variables defined in {} will be reclaimed by the garbage collector after {} is executed (this sentence is my guess).

   Classification of code blocks:

       Static code block: A code block modified by static at the member position of the class. Initialize the class . Static code blocks can only be executed once! ! ! !
       Construction code block: The part enclosed in {} at the member position of a class. Multiple constructors can be placed in the constructor block to initialize the object .
       Constructor: This concept should be understood in the first phase of object orientation.      

       Local code block: In main() , define the life cycle of the variable. Give the variable its life cycle .

    Priority of code blocks:

        Static code block > Local code block > Constructor code block > Constructor method

Example:

class Code{
	
	//Static code block: the second highest priority, the second execution
	static{
		int x = 1000 ;
		System.out.println(x);
	}
	
	// member location
	{
		int x = 100 ;
		System.out.println(x);
	}
	//Construction method
	public Code() {
		System.out.println("code");
	}
	
	//construct code block
	{
		int y = 200 ;
		System.out.println(y);
	}
	
	// constructor with parameters
	public Code(int a) {
		System.out.println("code");
	}
	
	//static code block
	static {
		int y = 2000 ;
		System.out.println(y);
	}
}
public class CodeDemo {
	
	public static void main(String[] args) {
		
		//Local code block: the highest priority is executed first
		{
			int x = 10 ;
			System.out.println(x);
		}
                //local code block
		{	
			int y = 20 ;
			System.out.println(y);
		}
		
		//Create an object of the Code class
		Code code = new Code() ;
		System.out.println("--------------------");
		Code code2 = new Code() ;
		System.out.println("--------------------");
		Code code3 = new Code(100) ;
	}
}
        Execution order: The main method is loaded first. In the main method, there is only one local code block and three objects are created, so they are executed in order. After executing the local code block, we start to create the object of Code. Before creating the object, we need to load the class. When loading the class, because there are two static code blocks, we execute the two static code blocks in priority order. The static code block is executed only once, and the static code block no longer exists after execution. Then we execute the local code block in the Code class, execute the construction code block after execution, and finally construct with parameters.
So the result of our console output is:
1000
2000
100
200
code
--------------------
100
200
code
--------------------
100
200
code

inherit

What is inheritance?

        Why introduce inheritance?

            When we create multiple classes with the same properties or behaviors, the code will be redundant due to the high repetition of the content, so we take out the parts with the same properties or methods and send them to an independent class, this independent class It is called the parent class, and the extracted person is called the subclass. The subclass can inherit all of the parent class, except for the constructor, which we can access by calling the method.

        Inheritance is to extract the common content of multiple classes as an independent class, and create a relationship between this independent class and the extracted class, which is called inheritance relationship.

Inherited syntax    

    class parent class name {

    }
    class subclass name extends superclass name {

    }

    The grammar stipulates that there cannot be multiple inheritance for inheritance, only single inheritance. But multi-level inheritance can be supported.

The benefits and features of inheritance

    Inheritance provides code reusability and solves the problem of code bloat.
    A subclass inherits everything from the parent class, including member variables, member methods, and even private variables and methods. However, subclasses cannot directly use the private resources of the parent class, and can only access private resources indirectly through the public access of the parent class.
    Subclasses cannot directly inherit the constructor of the superclass , but they can be accessed through the super keyword.
    Inheritance is used when the parent class belongs entirely to the child class.

    Subclasses that inherit the superclass must access the no-argument constructor of the superclass by default. Reason: If the data is not initialized, the parent class should be initialized first, and then the subclass should be initialized - hierarchical initialization.

   

example

class Father{//This is a parent class
	int money;
	private int age;
	private String name;
	public void Fa() {
		System.out.println("i am father");
	}
	private void Fa1() {
		
	}
	public Father() {
		super();
	}
	public Father(int money, int age, String name) {
		super();
		this.money = money;
		this.age = age;
		this.name = name;
	}
	public int getMoney() {
		return money;
	}
	public void setMoney(int money) {
		this.money = money;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	
	
	
	
}

class Son extends Father{//This is a subclass
	private String hoby ;
	int num;
	
	
	public void Aloha(){
		System.out.println("i am son");
	}
	public Sound() {
		super();
	}
	
	public Son(int money, int age, String name,String hoby) {
		super(money, age, name);
	}
	public String getHoby() {
		return hoby;
	}
	public void setHoby(String hoby) {
		this.hoby = hoby;
	}
	public int getNum() {
		return num;
	}
	public void setNum (int num) {
		this.num = num;
	}
	
	
}
public class time8_50 {

	public static void main(String[] args) {
		Son s = new Son();
		//The private member variables and private member methods of the parent class cannot be accessed through the object s.	
		s.Fa ();
		s.setNum (10);
		s.setHoby("pingpang");
		System.out.println(s.getNum() + "-"+s.getHoby());
		
		//create object of parent class
		Father f = new Father();
		//After creating the object of the parent class, the child class object can call the parent class's methods and non-private variables
		s.setAge(80);
		s.setMoney(210);
		s.setName("zhangsan");
		
		System.out.println(s.getName() + " " + s.getAge() + " " + s.getMoney() + " son:" + s.getNum() + " " + s.getHoby());
	}

}

super keyword

    The this keyword is used to refer to the member location in the class, especially when the local variable and member variable have the same name.
    The role of super is similar to this. super is used to point to the member position in the parent class, and it is also a keyword that can distinguish the parent class from the subclass and the same name in the subclass method.

E.g:

class Father1{
	public int num = 100;
}
class Son1 extends Father1{
	public int num = 10;
	public void show() {
		int num = 5;
		System.out.println(num);//Search order: in the subclass method ---> subclass member position ---> parent class member position can not reach the parent class method
		System.out.println(this.num);//this can specify member variables when member variables and local variables have the same name
		System.out.println(super.num);//super can directly point to variables in the parent class when member variables and local variables have the same names as the variables in the parent class.
	}
	
}
public class time11_02 {
	public static void main(String[] args) {
		Son1 s =new Son1();
		s.show();
	}
}

The result of the console output is:
5
10
100

Usage of super(&this) keyword

        All are accessible: member variable this.member variable;//access member variable of current class super.member variable;//access member variable of parent class
                          Member method this. method name;//Access the member method of the current class super. Method name;//Access the member method of the parent class
                          Constructor this();//Access the parameterless structure this(" "); //Access the parameterized structure of the current class
                                             super(); // access the no-argument construction of the parent class super(" ");//access the parametric construction of the parent class

polymorphism

        At the same moment, it manifests a different state.
   The premise of polymorphism:

        1. There must be an inheritance relationship
        2. There must be a method to override

        3. There must be a reference to the parent class pointing to the object of the child class (upcasting)

Access Features:
        parent class name fu = new child class name();

class Fu{
	int num = 10 ;
	public void Num() {
		System.out.println("Test class of parent class");
	}
}

class Zi extends Fu{
	int num = 20 ;
	public void Num() {//Method override
		System.out.println("Subclass test class");
	}
}
public class Test1 {

	public static void main(String[] args) {
		Fu f = new Zi();// The reference of the parent class points to the object of the child class
		System.out.println(f.num);
		f.Num();
		
	}
}

The result of running the above code is that the output num = 10; the output of Num is "subclass test class". We can conclude that for member variable references, we pay attention to the parent class; for member methods (non-static), because there are method overrides, we have to pay attention to the subclass. For static methods, because the static method is loaded with the class loading, it is not a method rewriting, so you still need to look at the parent class after creating the object.

The benefits of polymorphism: improve code reusability (provided by inheritance); improve code scalability (provided by polymorphism).
E.g:

class Animal{
	public void eat() {
		System.out.println("吃");
	}
	public void sleep() {
		System.out.println("睡");
	}
}

class Dog extends Animal{
	public void eat() {
		System.out.println("狗吃屎");
		
	}
	public void sleep() {
		System.out.println("Dog sleeps");
	}
}
class Cat extends Animal{
	public void eat() {
		System.out.println("Cat eats cat food");
	}
	
	public void sleep() {
		System.out.println("Cat sleeps");
	}
}
class Pet extends Animal{
	private Pet() {//Do not let Pet objects be created
		
	}
	public static void PetTest(Animal a) {
		a.eat();
		a.sleep();
	}
}
public class Test2 {

	public static void main(String[] args) {
		Animal c = new Cat();
		Animal d = new Dog();
		Pet.PetTest(c);
		Pet.PetTest(d);
	}

}

This can greatly reduce the redundancy of the program when repeating an action.

Memory diagram for downcasting (casting):

class Animal2{
	public void eat() {
		
	}
}

// cat class
class Cat2 extends Animal2 {
	public void eat() {}
	
	public void playGame() {}
}

//dog class:
class Dog2 extends Animal2{
	public void eat() {}
	
	public void lookDoor() {}
}

// test class
public class DuoTaiDemo5 {

	public static void main(String[] args) {
		
		//in memory is the cat
		Animal a = new Cat() ;
		
		// downcast
		//restore to cat
		Cat c = (Cat)a;
		
		// becomes a Dog in memory
		a = new Dog() ;
		//restore to dog
		Dog d = (Dog)a ;
		
		Cat cc = (Cat)a;//This sentence will convert exception
	}
}

Example 2:
class Person{
	public void eat() {
		System.out.println("Eat...");
	}
}

//southern
class SourthPeople extends Person{
	public void eat()	{
		System.out.println("Southerners eat rice...");
	}
	
	// unique function
	public void business() {
		System.out.println("Southerners love doing business...");
	}
}

//northern
class NorthPeople extends Person{
	public void eat(){
		System.out.println("Northerners love to eat noodles...");
	}
	// unique function
	public void yanJiu() {
		System.out.println("Northerners love to study...");
	}
}
// test class
public class DuoTaiTest2 {

	public static void main(String[] args) {
		// polymorphism: upcast
		Person p = new SouthPeople() ;//Upcast cannot access subclass-specific things
		p.eat();
		
		// downcast
		SourthPeople sp  = (SourthPeople)p;//sp指向SourthPeople
		sp.business();
		System.out.println("-------");
		
		//Actual opening: what class is it, what class object is given
		SourthPeople sp2 = new SourthPeople() ;
		sp2.eat();
		sp2.business();
	}
}
SouthPeople sp = (SourthPeople)p;//sp points to SouthPeople needs special understanding! ! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325849999&siteId=291194637