Three object-oriented features of day8

day8_ Three characteristics of object oriented

1, Encapsulation

  • Concept:

    Encapsulation( Encapsulation)
    Hide the internal implementation details of the object as much as possible, control the user's modification and access rights to the object, and ensure the security of internal attributes.
    

    Encapsulation: Encapsulation

Packaging in life:

Unsafe design:

class Account{
    String no;//Card number
    String password;//password
    double balance;//balance
}

Create object:

Account ac=new Acccount();
//set a property
ac.no="whj123455";//Illegal card number
ac.password="8";//Illegal password
ac.balance=150.2222221;//Illegal balance

//Access properties
System.out.println( ac.no );
System.out.println( ac.password );
System.out.println( ac.balance );

You can access and modify properties at will, destroy the original state of the object, and the design is unsafe.

(1) private keyword
  • Modifier: modifies each component in the program. The modified component has different characteristics and permissions.

  • Modifiers: decorate individual components in a program

  • Characteristics of private: the attributes and methods of private rhetoric can only be accessed in this class

    1. private Represents private and can modify properties and methods
    2. Components of rhetoric can only be in this class(class)Used in, invisible to the outside
    

    Example:

    MyClass class:

    package com.baizhi;
    public class MyClass{
    	int a;
    	private int b;
    	public void ma(){}
    	private void mb(){}
    }
    

    TestMyclass class:

    package com.baizhi;
    public class TestMyClass{
    	public static void main(String[] args){
    	   MyClass mc=new MyClass();
    	   mc.a=10;
    	   mc.ma();
    	   System.out.println(mc.a);//Can access
    	   mc.b=20;//Compilation error, no access
    	   mc.mb();//Compilation error, no access
    	}
    }
    
    TestMyClass.java:8: error: b Can be in MyClass Medium access private
               mc.b=20;
                 ^
    TestMyClass.java:9: error: mb()Can be in MyClass Medium access private
               mc.mb();
                 ^
    2 Errors
    

    (2) Privatization attributes and methods [key applications]

  • Use private to modify attributes (variables), privatize attributes or methods (implementations), and control access permissions

Example:

class Account{
    private String no;      //Card number
    private String password;  //password
    private double balance;    //balance
}

class TestAccount{
    public static void main(String[] args){
        Account ac = new Account();
    //set a property
    ac.no = "ldjwi10293";  //Compilation error, no access
    ac.password = "8";      //Compilation error, no access
    ac.balance = 150.800000001;//Compilation error, no access

    //Access properties
    System.out.println( ac.no );//Compilation error, no access
    System.out.println( ac.password );//Compilation error, no access
    System.out.println( ac.balance );//Compilation error, no access
    }
}
  • Unreasonable transitional security
If all properties or methods of a class are private, the objects of that class have no value.
Controlling access permissions is not one size fits all. In some cases, you also need to access properties or modify properties.
(3) Provide a way to access or modify private members (get/set method) [key application]
  • Solve the problem of excessive safety and reasonably control the internal attribute safety.

  • Provide get methods for accessible properties

Syntax:

public The return type that is consistent with the return value of the property get Attribute name(){//Property names in method names are capitalized
    return Attributes;//The return value type is the same as the property class value
}
  • Provide a set method for properties that can be modified

    Syntax:

    public void set Attribute name(Parameter parameter name){
        this.Attribute name=Formal parameter name;//The formal parameter type is consistent with the attribute type
            //The formal parameter name is consistent with the attribute name
            //Property names in methods are capitalized
    }
    

    Example:

Accoun class:

package com.baizhi;
public class Account{
	private String no;//Card number
	private String password;//password
	private double balance;//balance
	  
	  /*
	  public Return type get property name () {/ / the property name in the method name is capitalized
		return Attributes// The return value type is the same as the property class value
		}
*/
	  public String getNo(){//Get card number
	    return no;//The return value is decimal
	  }
	  /*
	  public void set Attribute name (parameter name){
			this.Attribute name = parameter name;
			
			//The formal parameter type is consistent with the attribute type
			//The formal parameter name is consistent with the attribute name
			//Property names in methods are capitalized
	}
	  */
	  public void setNo(String no){//Set card number
			this.no=no;
	  }
	  
	  public String getPassword(){//Get password
	     return password;
	  }
	  public void setPassword(String password){
				this.password=password;//Set password
	  }
	  
	  public double getBalance(){
	         return balance;
	  }
	  
	  public void setBalance(double balance){
			this.balance=balance;
	  }
	   
}

TestAccount:

package com.baizhi;
public class TestAccount{
	  public static void main(String[] args){
			Account ac=new Account();
			//Set properties (after encapsulation)
			ac.setNo("52212119991123");
			
			ac.setPassword("whj563135");
			
			ac.setBalance(2000000000);
			//After encapsulation, access the properties
			System.out.println("Card No.:"+ac.getNo());
			System.out.println("password"+ac.getPassword());
			System.out.println("Deposit:"+ac.getBalance());
	   }
}

result:

Card No.: 522119991123
 password whj563135
 Deposit: 2.0E9

(4) The actual function of get/set method
  1. Verify the validity of data before assignment

Example:

 class Account{
      private String no;      //Card number
      private String password;    //password
      private double balance;    //balance
      
      //.. slightly
      public String getPassword(){  //Get password
          return password;
      }
      public void setPassword(String password){//Set password
          if(password.length!=8) return;//If the password is not 8 digits, it will jump out
          this.password = password;
      }

  }

Gets the number of characters in the string. Use: string length

Significance of encapsulation: for example, supermarket management during the epidemic

1. No packaging: if the door of the supermarket is unattended and unmanaged, the safety of customers and goods cannot be guaranteed.
2. Private property: if all entrances and exits of the supermarket are sealed, it is too safe.
3. After encapsulation: set exit( get)And entrance( set)Add scanners and other equipment at the exit and entrance to protect the safety of customers and commodities.

  1. Set read-only properties

    Method: only get method is provided, not set method

    Example:

 class IdCard{          //ID
      private String id;    //ID number
      private String name;    //full name

      public String getName(){  //Get name
          return name;
      }
      public void setName(String name){  //Set name
          this.name = name;
      }
      public String getId(){  //Get ID number
          return id;
      }
  }
  1. Flexible camouflage attribute

    The data obtained or set is inconsistent with the property

    Example:

    class Person{      //human beings
        private int age;  //Age
        private boolean sex;//Gender
        
        public void setAge(int age){
          this.age = age;    
        }
        public int getAge(){
            return 18;//Forever 18
        }
        
        public void setSex(int sex){
            if(sex==1) 
                this.sex = true;//Hide attribute real type
        }
        public boolean getSex(){
            return sex;
        }
        
    }
    
    1. Private methods are more secure and can only be called internally

      Example: when the user uses the computer, turn it on

class Computer{
    public void on(){//Power on
        //Power supply and self inspection
        startFun();
    }
   
    private void startFun(){
        //Power supply, self inspection and speed adjustment
    }
}
(5) Summary
  1. The meaning of encapsulation: hide the internal implementation details of the object as much as possible, control the user's modification and access rights to the object, and ensure the security of internal attributes.

  2. Implementation of encapsulation:

    1. Property private. use private Decorate each attribute
    2. Provide public information as needed get or set Methods, both methods shall be provided without special circumstances.
    	set:Method is used to set a property and assign a value to the property
     get:Method to get the value of the property
        
    
  3. Benefits of encapsulation

    Methods are used to control the operation of member variables, which improves the security of the code
     The code is encapsulated by method, which improves the reusability of the code
    

2, Inherit

  • Concept:

    Inherit( inheritance)
    Restore of objective transactions is a relationship
    

    Encapsulation: Encapsulation

    inheritance: inheritance

    (1) is a relation
  • What is a kind of what, for example:

Lemon is a kind of fruit (Apple) is a Fruit)
Mangosteen is a kind of fruit (mangosteen) is a Fruit)
A dog is an animal (dog) is a Animals)
Mechanical keyboard is a kind of keyboard (mechanical keyboard) is a (keyboard)
  • Characteristics of is a relationship: the former must have the characteristics (attributes) and behavior (Methods) of the latter
(2) is a relation in computer
  • characteristic:

    1. In computer is a Relationship is called inheritance relationship, which is a kind of relationship(object)Relationship with class (object).
    2. The former is called parent class, base class or super class, and the latter is called child class or derived class.
    3. When the inheritance relationship is established, the subclass can also "own" the features (properties) and behaviors (Methods) in the parent class.
    
  • Inheritance syntax: table name is a relationship when defining a class

class Class name extends Parent class name{

}
(3) Inheritance effect
  • Subclasses can inherit properties or methods from the parent class*

    Example:

    package com.baizhi;
    public class Animal{
       String name;
       int age;
       public void sleep(){
          System.out.println("Sleep at night");
       }
       public void eat(){
    		 System.out.println("eat rice");
       }
      
    
    }
    
    package com.baizhi;
    public class Dog extends Animal{
    	public static void  main(String[] args){//don defines the properties and methods in Animal
    	    Dog dog=new Dog();
    		dog.name="Xiao Huang";
    		dog.age=3;
    		dog.sleep();
    		dog.eat();
    		System.out.println(dog.name);
    		System.out.println(dog.age);
    
    	}
    }
    

If the Dog class inherits the Animal class, the Dog class will obtain the properties and methods in the Animal class. For example, create a Dog object and access the sleep and eat methods defined in Animal

public static void main(String[]args){
    Dog d = new Dog();
    d.sleep();//Although the sleep method is not defined in the Dog class, Dog inherits Animal, so Dog can also call the methods in Animal
    d.eat();
}
  • Classroom exercises:

    package com.baizhi;
    public class TestInheritance{
    	public static void main(String[]args){
    		Dog d = new Dog();
    		d.eat();
    		d.sleep();//The subclass does not need to be defined. It calls the eating method and sleeping method of the parent class
    		
    		Cat cat=new Cat();
    		cat.eat();
    		cat.sleep();
    	}
    }
    
    //Animals
    class Animal{
    	String name;
    	int age;
    	//Eating method
    	public void eat(){
    		System.out.println("Animal eat()");
    	}
    	//Sleeping method
    	public void sleep(){
    		System.out.println("Animal sleep()");
    	}
    }
    
    //Dog dog
    class Dog extends Animal{
    	String name;
    	int age;
    	//run
    	public void run(){}
    	//call
    	public void shout(){}
    	//Swimming
    	public void swim(){}
    }
    
    //Cat cat
    class Cat extends Animal{
    	String name;
    	int age;
    	public void run(){}
    	public void shout(){}
    }
    //Output results:
            Animal eat()
            Animal sleep()
            Animal eat()
            Animal sleep()
    
  • The performance of inheritance in memory [your father becomes a part of you]

    The parent object will become a part of the child object, so you can use the properties or methods in the parent object through the child object

    Object in heap memory, there will be a separate super area to store the data of the parent class

  • When you create a subclass object, the JVM automatically creates the parent object as part of the subclass object

  • If the property or method of the parent class is private, it can be inherited but does not have permission to use, occupying memory space

  • My relatives gave me lucky money. My father took it away. He put the lucky money in the safe and gave it to you. The lucky money can't be used. It's yours. You can't use it

  • Transitivity of inheritance, multi-level inheritance

    The parent class can also have a parent class, and the parent class of the parent class can also have a parent class... And so on, properties and methods will always be passed down

Example:

package com.baizhi;
public class TestInheritance3{
	public static void main(String[]args){
		MyClass mc = new MyClass();
		System.out.println( mc.e );//Subclass properties
		System.out.println( mc.d );//Parent class properties
		System.out.println( mc.c );//Grandfather class properties
		System.out.println( mc.b );//Taiye attribute
		System.out.println( mc.a );//Ancestral class attribute
		
	}
}

class MyClassA{
	int a=10;
}
//MyClassB is a MyClassA
class MyClassB extends MyClassA{ 
	int b=20;
}
class MyClassC extends MyClassB{
	int c=30;
}
class MyClassD extends MyClassC{
	int d=40;
}

class MyClass extends MyClassD{
	int e=50;
}

⚠️ Constructors cannot be inherited by subclasses. Only one parent can inherit

⚠️ The inheritance relationship in Java is single inheritance. A class can only have one direct parent class, which can be inherited indirectly. Multi level inheritance is supported. Subclasses can inherit properties and methods in all parent classes

Features: inheritance is a single inheritance, not multiple inheritance, and supports multi-level inheritance

  • Member access characteristics in inheritance
1. Subclass local range lookup
2. Subclass member range lookup
3. Parent class member variable lookup
4. If not, report an error
(4) Access modifier
  • Function: control the visible (usable) range of components

    This categoryThis categoryIt has nothing to do with steamed stuffed bunDifferent steamed stuffed bun classesDifferent packages are not subclasses
    private❤️
    (default)❤️❤️
    Protected❤️❤️❤️
    public❤️❤️❤️❤️
  • private cannot be accessed in other classes and can only be used in this class

    package com.baizhi;
    public class TestModifier{
    	public static void main(String[]args){
    		MyClass mc = new MyClass();
    		System.out.println( mc.a );//private cannot be accessed
    		System.out.println( mc.b );//(default)
    		System.out.println( mc.c );//protected
    		System.out.println( mc.d );//public
    	}
    }
    
    class MyClass{
    	private int a;//Private
    	int b;//default
    	protected int c;//Protected
    	public int d;//Open
    	
    	public void m1(){
    		System.out.println( a );//private can access
    		System.out.println( b );//(default)
    		System.out.println( c );//protected
    		System.out.println( d );//public
    	}
    	
    }
    
  • protect can only be used in the same package

  • Default (default) different packages are not used in subclasses

⚠️ When there is no access modifier in front of the component, it defaults to (default) modifier

(5) Method Override (key concept)
  • What animals like to eat is a general term for animals. To cover and rewrite what dogs and cats like to eat is to solve what animals like to eat and how to eat. Rewrite the parent method in the child class. Dogs like to eat bones. They use their own, and those they don't use the parent

  • Method overload: overload. Define multiple methods with the same name in a class. The parameter tables (parameter types, order and number) are different, and the return value types can be different

  • Override annotation: it is used to check whether the current method is an overridden method

  • Usage scenario

    When the method of the parent class is no longer applicable to the child class or cannot meet the needs of the child class, the method of the parent class can be overridden
     When it is called again, the overridden method will be called
    
  • Syntax: the repair character is the same or wider, and the method name, parameter table and return value type are the same

    The return value type, method name, parameter table and modifier are the same or wider
    
    public class TestOverride{
      public static void main(String[]args){
        Sub sub = new Sub();
        sub.m1();//Call the m1 method after subclass coverage to print m1 in sub
      }
    }
    
    class Super{
      public void m1(){
        System.out.println("m1 in super");
      }
    }
    
    class Sub extends Super{
      //Overwrite: the access modifier is the same or wider, and the return value type, method name and parameter table are the same
      public void m1(){
        System.out.println("m1 in sub");  
      }
    }
    

  • If the return values are different, they are not overwritten or rewritten, and errors will be directly compiled

  • Different method names and parameter tables are overloaded rather than overwritten

  • If the parent class is private, the child class can write the return value type without error, because the private parent class cannot be overwritten

  • Static methods cannot be overridden if the subclass also has the same method, which is not the method of the overridden parent class

  • Method rewrite considerations:

1. Method overrides (overrides) cannot call private member methods of a parent class
2. Subclass access method cannot be lower
  • The difference between method override and method overload
1. Method overrides occur between parent and child classes. Syntax requirements: the access modifier is the same or wider, and the return value type, method name and parameter table are the same.

2. Method overloading can be carried out in this class or between parent and child classes. Syntax requirements: the method name is the same, the parameter table is different, and there are no other requirements.

Example:

package com.baizhi;
public class Print{
	public static void main(String[] args){
		Sub sub = new Sub();
		sub.m1();//Call the m1() method in the parent class
		sub.m1(10);//Call m1(int) method in subclass
    }
}

class Super{
  public void m1(){
    System.out.println("m1 in super");
  }
}

class Sub extends Super{
  //It constitutes an overload with the method of the parent class, with the same method name and different parameter table
  public void m1(int n){
  
  }
}
	

⚠️ Note: the override method name is the same as the parameter name, and the overload method name is different from the parameter name

(6) Object creation process
  1. Allocate space
  2. Initialize properties
  3. Call constructor
1. Allocate space (parent)+Subclass)
2. Initialize parent class properties
3. Call the parent class constructor
4. Initialize subclass properties
5. Call subclass constructor

⚠️ Follow the order from parent to child. If the parent class has a parent class, initialize the parent class of the parent class first, and so on

//First Grandpa, then Dad, first dad, then me
package com.baizhi;
public class TestInit{
	public static void main(String[]args){
		//Create subclass objects
		new Sub();
	}
}


class Super {
	public Super(){
		System.out.println("Super()");//Execute the of the parent class first
	}
}

class Sub extends Super{
	public Sub(){
		System.out.println("Sub()");//Post execution subclass
	}
}

new Sub();
//Print:
    //Super()
   // Sub()
  • Constructors cannot be inherited and understood
 Constructors can be understood in this way. Constructors are used to create objects. The image is that your father and your mother have a constructor, which will cause your appearance. Your Lord and your milk also have a constructor, which will cause your father to appear. If the constructor can inherit, your father and your mother can not have their own constructor. Then you can directly get out of your grandpa's and grandma's constructors. This will cause you and your father to be born out of order
  • The attribute is assigned with parameters, and the object is created without parameters

    1. Constructors cannot be inherited, so they cannot be overridden, but they can be overloaded.
    
    2. Reason: constructors are a way to produce objects. If they can be inherited, then objects can be copied. A subclass can generate a parent object through an inheritance constructor, so that the subclass reference points to the parent object, java Downward transformation is not supported, only upward transformation.
    
  • java problem: it's not that the parent class constructor cannot be inherited by the child class constructor. What's the matter with the program in the figure below?

1. A subclass cannot inherit the constructor of the parent class.
2. However, when creating an object of a subclass, a constructor of the parent class must be called before calling a constructor of the subclass to initialize the data members inherited from the parent class. That's what the picture shows.
(7) super keyword
  • This represents the current object and can access properties or methods. this() can call other constructors of this class in the constructor and must be placed in the first row of the constructor.

  • Meaning: super refers to the reference of parent class object

  • Function: when the attribute of the subclass conflicts with the name of the parent class, use super Represents the properties or methods of the parent class to resolve naming conflicts

  1. Use super Accessing properties or methods in a parent class

When to use: when the method or attribute of the parent class is overridden by the child class, you can use super Accessing methods or properties of a parent class

  • super and this keywords
1. this$super
	this:Access the member variables and constructors of this class
	super: Access the member variables and constructors of the parent class
2. Member variable
	this.Member variable: access the member variable of this class
	super.Member variable: access the member variable of the parent class
3. Member method
	this.Member method: access the member method of this class
	super.Member method:Accessing member methods of the parent class
4. Construction method
	this():Access the constructor of this class and put it on the first line of the constructor
	super(): The constructor that accesses the parent class is placed on the first line of the constructor

[the external link picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-dV878yOI-1628507638161)(F: \ Baizhi note \ note content \ img\image-20210809100108467.png)]

Example: accessing the properties of the parent class

package com.baizhi;
public class Print{
	public static void main(String[] args){
		Sub sub = new Sub();
		sub.m1();//Call m1() method in subclass
	
    }
}
	class Super{
	   int a=10;//Parent class properties
	}

	class Sub extends Super{
		int a=20;//Subclass properties
		public void m1(){
		int a=30;//local variable
		System.out.println(a);//Print local variables
		System.out.println(this.a);//Print variables of this class
		System.out.println(super.a);//Print variables of parent class
	  
	  }
	}
	
answer:
    30
    20
    10

Example: accessing the method whose parent class is overridden

class Super{
  public void m1(){
    System.out.println("m1 in super");
  }
}
class Sub extends Super{
  public void m1(){//Override method of parent class
    super.m1();//Call the m2 method in the parent class
    System.out.println("m1 in sub");
  }
}
  1. Use super() to specify the construction method used when automatically creating a parent object. The parameterless construction method of the parent class is used by default
  • Usage timing: use the parent class constructor to initialize the parent class attribute (unnecessary operation)
1. super() Parameterless construction means that the parameterless construction method of the parent class creates an object
2. super(Argument) Indicates that the parent class object is constructed using the parameterized construction method of the parent class
class Animal{
  String name;
  int age;
  public Animal(){
      System.out.println("Super()");
  }
  public Animal(String name, int age){
    this.name = name;
    this.age = age;
  }
}

class Dog(){
  public Dog(String name,int age){
    //Assign a value to an attribute using a parent class parameterized construct
    super(name,age);
  }
   public Dog(){
     super();//Represents a parameterless constructor that uses a parent class
       System.out.println("Sub()");
  }
}
  • The subclass calls the private method of the parent class
package com.baizhi;
public class TestSuper{
	public static void main(String[]args){
		Dog d = new Dog("Xiao Hei",5);
		
		System.out.println( d.getName() );
		System.out.println( d.getAge() );
	}
}

class Animal{
	
	private String name;
	private int age;
	
	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;
	}
	
}

class Dog extends Animal{
	public Dog(){}
	public Dog(String name,int age){
		//Assign a value to the attribute with the help of the set method of the parent class
		super.setName( name );//If there is no conflict, you can not write. You call the get and set methods, not the constructor
		super.setAge( age );
	}
}

  • Use the parameterized construction method of the parent class to assign a value to the parent class attribute

    package com.baizhi;
    public class TestSuper{
    	public static void main(String[]args){
    		Dog d = new Dog("Xiao Hei",5);
    		
    		
    		System.out.println( d.getName() );
    		System.out.println( d.getAge() );
    	}
    }
    
    class Animal{
    	
    	private String name;
    	private int age;
    	
    	public Animal(){}
    	public Animal(String name,int age){
    		this.name = name;
    		this.age = age;
    	}
    	
    	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;
    	}
    	
    }
    
    class Dog extends Animal{
    	public Dog(){}
    	public Dog(String name,int age){
    		//Use the parameterized construction method of the parent class to assign a value to the parent class attribute
    		super(name,age);
    		//Assign a value to the attribute with the help of the set method of the parent class
    		//setName( name );
    		//setAge( age );
    	}
    }
    
(8) Modifier
  1. package folder

  2. import package

  3. final: it can modify member methods, member variables and classes

    1. final Modifier class: cannot be inherited. It can have a parent class and no child class
    2. final Rhetorical methods cannot be rewritten
    3. final A rhetorical variable cannot be re assigned, indicating that the variable is a constant
        final Rhetorical local variables:
        1. The basic type variable of rhetoric, and the value of the basic type cannot be changed
        2. Rhetoric refers to a variable of type. Rhetoric refers to that the address cannot be changed, but the value inside can be changed
    

    ⚠️ final rhetoric refers to variables of type. The address cannot be changed, but the value inside can be changed

    1. static:static method means static. It can be used to describe member variables and member methods

      1. Shared by all objects of the class, which is also the condition for us to judge whether to use static keywords
      2. It can be called by class name, of course it can be called by object name [class name is recommended]
      
      • Features of static shared data

        1. Non static member method
            *Can access static member variables
            *Access to static member methods
            *Can access non static member variables
            *Access to non static member methods
        2. Static member method
            * Can access static member variables
            *Access to static member methods
         3. Static member methods can only access static members
        
(9) Access characteristics of construction methods in inheritance

Note: all constructors in inherited subclasses will access the parameterless constructors of the parent class by default

Subclasses inherit the data and methods of the parent class of the parent class. Therefore, the parent class must be initialized before subclass initialization. The reason is that the first default statement before each subclass constructs a method is super()

Note: this(...) super(...) must be placed in the first line of the construction method, and the two cannot coexist

3, Polymorphism

  • Concept: different forms of the same object at different times
Polymorphism( Polymorphism)
Use the parent class reference to point to different subclass objects, and different subclass objects will eventually show different "morphological characteristics"
package com.baizhi;
public class TestPloymorphism{
	public static void main(String[]args){
		//Embodiment of polymorphism
		Animal a1 = new Dog();
		Animal a2 = new Cat();
	}
}

//is a relation
class Animal{
	public void eat(){}
	public void sleep(){}
}
//Dog is a Animal
class Dog extends Animal{}
//Cat is a Animal
class Cat extends Animal{}
  • Polymorphic premise

    1. There should be inheritance and implementation relationships
    2. There should be method rewriting(@override)
    3. A parent class reference should point to a child class reference super()
    
  • Expression of polymorphism (Syntax): use parent class references to store subclass objects

class Animal{}
class Dog extends Animal{}//Dog is a Animal
class Cat extends Animal{}//Cat is a Animal

Animal a1 = new Dog();//Embodiment of polymorphism
Animal a2 = new Cat();//Embodiment of polymorphism

(1) Characteristics

1. Member variable: compile to see the parent class, run to see the parent class
2. Member method: compile to see the parent class and run to see the child class
1. The subclass object type is always the same [member variable, compile to see the parent class, run to see the parent class]

Example:

    package com.baizhi;
    public class TestPloymorphism2{
        public static void main(String[]args){
            //Embodiment of polymorphism
            //Animal a1 = new Dog();
            //Animal a2 = new Cat();
            Dog d1 = new Dog();
            Pet p = d1;
            Animal a = d1;

            System.out.println( d1 );
            System.out.println( p  );
            System.out.println( a  );
        }
    }
    //is a relation
    class Animal{
        public void eat(){}
        public void sleep(){}
    }
    //Pet is a Animal
    class Pet extends Animal{
    }

    //Dog is a Pet
    class Dog extends Pet{}

    //Cat is a Animal
    class Cat extends Animal{}
    com.baizhi.Dog@15db9742
    com.baizhi.Dog@15db9742
    com.baizhi.Dog@15db9742

  1. During compilation, only the methods declared in the reference type [parent class] can be called

    Due to the existence of polymorphism, only when the program runs can we know what type the object stored in the parent class is, but the compiler cannot know. The compiler can only determine that the object stored in the reference is a subclass, and the subclass must have the methods in the parent class. Therefore, it can only call the methods declared in the reference type (parent class)

Scanner sc = new Scanner(System.in);
int n = sc.nextInt();

Animal a1;//The subclass object type it hosts cannot be confirmed at compile time
if(n%2==0)
  a1 = new Fish();
else
  a1 = new Bird();
//The compiler can only determine that there is no problem calling the method of the parent class    
a1.eat();
a1.sleep();

a1.fly();//error it is not certain that the Bird object must be stored in Animal
3. At runtime, if the subclass overrides the method in the parent class, the method overridden in the subclass will be executed.

When a method is called, the method in the object is called [member method, parent class for compilation and child class for operation]

Animal a1 = new Dog();
a1.eat();  //When running, call the method after subclass override
a1.sleep(); //Subclass call, not parent class,
//Running result: the dog gnaws at the bone
//       Animal sleep

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

class Dog extends Animal{
  public void eat(){
    System.out.println("The dog gnawed at the bone~~");
  }
}

  • The method or property responsible for calling this method is a subclass, not a parent (the method of eating is that dogs eat, not animals)

Proximity principle: if this class has, use the eat method of this class

  • Benefits: improve the extensibility of the code, use the parent type as the parameter when defining the method, and use the specific subtype to participate in the operation
  • Disadvantage: you cannot use unique members of subclasses

(2) Type conversion

  1. The subclass object is assigned to the parent class reference, and the parent class reference points to the subclass object, which is an upward transformation
Animal a = new Dog();
  1. The parent class reference (originally, only the method of the parent class can be called) is assigned to the child class reference (the method of the child class can be called) for downward transformation, and forced type conversion is required
Format: subtype object name=(Subtype) parent class reference
        Animal a = new Dog();
        //Downcast
        Dog d = (Dog) a;

Function: when it is necessary to call a unique method in a subclass, it is called through subclass reference after downward transformation

Animal a1 = new Dog();
//Downward transformation supports cast
//After cast, the compiler will not intervene
Dog d =(Dog) a1;

d.swim();//After the downward transformation, you can call the methods declared in the Dog class
d.shout();

⚠️ Note: during downward transformation, forced type conversion can only ensure that the compilation passes. If the types match, the following exceptions will occur at runtime

Animal a = new Cat();
Dog d = (Dog)a;//If the compilation passes, Java. Net appears at runtime Lang.classcastexception type conversion exception.
  • Example:
package com.baizhi;
public class TestPloymorphism4{
	public static void main(String[]args){
		Animal a = new Dog();
		a.eat();
		a.sleep();
		//Transform down to convert the reference type to a subclass type
		//Save the object stored in the a reference to the Dog type reference
		Dog d = (Dog)a;
		d.shout();
		d.run();
		d.swim();
	}
}
//is a relation
class Animal{
	public void eat(){}
	public void sleep(){}
}
//Pet is a Animal
class Pet extends Animal{
	
}

//Dog is a Pet
class Dog extends Pet{
	public void eat(){
		System.out.println("");
	}
	public void shout(){}
	public void run(){}
	public void swim(){}
}
//Cat is a Animal
class Cat extends Animal{
	public void shout(){}
	public void run(){}
}

//Bird is a Animal
class Bird extends Animal{
	public void shout(){}
	public void fly(){}
}


(3) instanceof keyword
  • Function: judge whether the object stored in the reference is compatible with a certain type

  • Strictly speaking, instanceof is a binocular operator in Java, which is used to test whether an object is an instance of a class

    ref instanceof cls 
    

    ref is the reference of an object and cls is the class name. If the object stored in the reference is compatible with cls, the result is true, otherwise it is false

    The instanceof operator can only be used as a judgment of an object.

  • Application scenario: it is used to find a certain type of object or use instanceof for judgment during downward transformation to avoid type conversion exceptions

    Example:

    Animal a = ....;
    
    //Judge whether the object stored in a reference is of Dog type
    if( a instanceof Dog ){
      System.out.println( "Dog in a" );
      Dog d = (Dog)a;//Cast type
      d.shout();//Call the method in the Dog class
    }
    
  • Determine whether the elements in the array are of a certain type

    package com.baizhi;
    public class TestInstanceof2{
    	public static void main(String[]args){
    		//An array with a length of 10 is created, and each space can store an Animal object
    		Animal[] as = new Animal[10];
    		//Store the Dog object in the as array
    		as[0] = new Dog();
    		as[1] = new Cat();
    		as[2] = new Bird();
    		as[3] = new Dog();
    		as[4] = new Cat();
    		as[5] = new Bird();
    		as[6] = new Bird();
    		as[7] = new Dog();
    		as[8] = new Cat();
    		as[9] = new Cat();
    		int count = 0;
    		//Count the number of all Dog objects in the as array
    		for(int i=0; i<as.length; i++){
    			//Get an Animal object from the Animal array
    			Animal a = as[i];
    			//If the object type stored in the a reference is Dog
    			if( a instanceof Dog )
    				count++;//Statistical quantity
    		}
    		System.out.println( count );
    		
    	}
    }
    

(3) Application of polymorphism (expansion)

  • Using polymorphism to shield the differences between subclasses makes the program more flexible, improves the scalability of the program and reduces the coupling between programs
  • Example: vending machine
public class TestVendingMachine{
    public static void main(String[] args){
        //Create vending machine object
        VendingMachine as = new VendingMachine();
        Beverage ibt = as.sell( 1 );//Selling goods
        System.out.println("What did you buy"+ibt.name+" Unit Price:"+ibt.price);
        Beverage ibt2= as.sell( 2 );//Selling goods
        System.out.println("What did you buy"+ibt2.name+" Unit Price:"+ibt2.price);

    }
}

//vending machine
class VendingMachine{
    //Selling method
    public Beverage sell(int n){//n indicates the number of the item
        switch( n ){//Return different items according to different numbers
            case 1:IceBlackTea ibt = new IceBlackTea("Green Ice Tea ",3D);
                return ibt;//Return iced tea object

            case 2:MilkTea mt = new MilkTea("U-loveit",5D);
                return mt;//Return milk tea object

            case 3:RedBull rm = new RedBull("Enhanced type",8D);
                return rm;
            default:return null;
        }
        //To satisfy grammar
    }
}
class Beverage{//Drinks
    String name;
    double price;
    public Beverage(){}
    public Beverage(String name,double price){
        this.name = name;
        this.price = price;
    }
}

class IceBlackTea extends Beverage{//Ice Black Tea
    public IceBlackTea(){}
    public IceBlackTea(String name,double price){
        super(name,price);
    }
}

class MilkTea extends Beverage{//tea with milk
    public MilkTea(){}
    public MilkTea(String name,double price){
        super(name,price);
    }
}

class RedBull extends Beverage{//Red Bull
    public RedBull(){}
    public RedBull(String name,double price){
        super(name,price);
    }
}

Added by Afrojojo on Wed, 29 Dec 2021 09:47:07 +0200