Encapsulation, inheritance and polymorphism of java

encapsulation

  • Characteristics of encapsulation: data can only be accessed through specified methods.
  • Hide the instance details of the class to facilitate modification and implementation.
  • Specific practical steps of packaging
    • Modify the visibility of attributes to restrict access to attributes, which is generally set to private.
    • Create a pair of setter and getter methods for each attribute, which are generally set to public for attribute reading and writing
    • Add attribute control statements (judge the legitimacy of attribute values) to the assignment and value taking methods.
public class Employee {
    private String name; // full name
    private int age; // Age
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        // Limit age
        if (age < 18 || age > 40) {
            System.out.println("Age must be between 18 and 40!");
            this.age = 20; // Default age
        } else {
            this.age = age;
        }
    }
public class EmployeeTest {
    public static void main(String[] args) {
        Employee people = new Employee();
        people.setName("Lili");
        people.setAge(35);
        System.out.println("full name:" + people.getName());
        System.out.println("Age:" + people.getAge());
    }
}

Output results
Name: Lili
Age: 35

inherit

  • Definition: extend an existing class to generate a new class. Existing classes are called parent classes, base classes, or superclasses, while newly generated classes are called subclasses or derived classes. In a subclass, you can not only include the properties and methods of the parent class, but also add new properties and methods.
  • Format: modifier subclass extends parent class {body of class}
  • Only one class is allowed to directly inherit from another class, that is, a subclass can only have one direct parent class, but can have multiple indirect parents, and there can only be one class name after the extends keyword.
  • Object is the top-level parent class (root class) of all classes, and all classes directly or briefly inherit the object class
    The following demonstrates the inheritance and rewriting of methods
public class father {
    double A(int x,int y){
        return x+y;
    }
    double B(int m,int n){
        return m*n;
    }
}

class son extends father {
    double A(int x,int y){
        return x+2*y;
    }
}

Main function

public class test {
    public static void main(String[] args) {
        son s=new son();
        System.out.println(s.A(1,2));

    }
}

Output result 5.0

Method overrides and attribute overrides under inheritance

There is an override relationship between the member methods of the subclass and the parent class, and there is an override relationship between the member variables of the subclass and the parent class.
If the member variable in the parent class is visible in the child class and the member variable name is the same, it is called attribute override.

  • int i=4 in parent class
  • int i=5 in subclass

When calling, i=5 shall prevail.

Restrictions on inheritance

  • Subclasses cannot directly access private members in the parent class.
  • Subclasses can inherit all non private member variables and methods from the parent class as their own members, but subclasses cannot directly access the private members of the parent class (including member variables and member methods). If private member variables need to be accessed, they can be implemented through getter and setter methods.
  • Members of private decoration can only be visible in this class body
class A{
	private int x;
	private void showX() { //Private method
		System.out.println(this.x);
	}
	public  void setX(int x) {
		this.x=x;
	}
	public int getX() {
		return this.x;
	}
}
class B extends A{  }  //Subclass B inherits parent class A
public class Demo2 {
	public static void main(String[] args) {
		B b=new B();
		b.setX(100);
		b.showX(); //Error prompt
	}
}
  • The construction of the parent class must be called by default before the construction of the subclass object (the default is to use the parameterless construction), so as to ensure that the object of the parent class is instantiated first, and then the subclass object is instantiated.

The difference between method override and method overloading

  1. Method overrides exist between subclasses and parent classes, and method overloads exist between member methods within a class.
  2. Method override means that the methods of the subclass and the methods of the parent class are completely consistent in three aspects: method name, number of parameters and parameter type; Method overloading means that the method has the same name, but the number of parameters or parameter types are different.
  3. When overriding a method, the access permission of the method in the subclass cannot be less than that of the parent class.
class A {
public void show(int x) {}
void display(double y) {}
}
class B extends A {	// Subclass B inherits parent class A
public void show(int x) {}  //Override the show method of the parent class
//Overloading the display method in the parent class
public void display(String msg) {}
}
 
public class Demo2 {
public static void main(String[] args) {
B b=new B();
b.show(10);//Call the show method of the subclass
}
}

super keyword

  1. Access the member variable with the same name hidden by the subclass in the direct parent class.

super. member variable name;

  1. Access the member method with the same name overridden by the subclass in the direct parent class.

super. member method name (parameter table);

  1. Call the constructor of the direct parent class. Constructor cannot be inherited_ In the subclass constructor, the first statement calls the constructor of the parent class by default, and not writing super() means that the parameterless constructor of the parent class is called by default_ Therefore, if a subclass wants to use the constructor of the parent class, it must be represented by the keyword super in the constructor of the subclass, and super must be the first valid statement in the constructor of the subclass.

super (parameter)// The statement must be the first valid statement of the constructor.

class Father{
  private int x=10;
  public Father(int x) {
     //By default, the null constructor of Father parent Object is called
     this.x=x;
  }
  public void show() { 
     System.out.println(this.x);
   }
}
class Son extends Father{
	private int y=20;
	public Son(int x,int y) {
		super(x);    //Call Father's constructor
		this.y=y;		
	}
	public void show() {  //Subclass overrides the method with the same name of the parent class
		System.out.println(this.y);
	}
	public  void print() {
		this.show();//Call the show method of Son
		super.show();//Call father's show method
	}
}

polymorphic

  • Definition: refers to the same behavior with multiple different manifestations.
  • Three conditions for realizing polymorphism:
    • 1. Inheritance: inherit or realize [one of two]
    • 2. Rewriting: Rewriting of methods [meaning embodiment: no rewriting, no meaning]
    • 3. Upward Transformation: the parent class reference points to the subclass object [fu p=new zi()]
  • Format of polymorphism:
    • Parent type variable name = new subclass object;
    • Parent class type: refers to the parent class type inherited by the child class object or the implemented parent interface type
  • Benefits of polymorphism:
    -Polymorphism allows us to use some methods of an object without caring about its specific type


For the boss, he doesn't care whether you are a lecturer or a teaching assistant. The only thing to do is to urge you to work.

  • Accessing methods and attributes in polymorphism
    • Accessing member variables in polymorphism: compile and run on the left (parent class)
      • If the parent class and the child class have the same member variable, but the assigned value is different, the one in the parent class shall prevail

If you call a member variable that only the parent class has but not the child class, an error is reported.

  • Accessing member methods in polymorphism: compile to the left, but run to the right

Both father and son have children first. If there is no child class, there is a parent class. Find the parent class upward

  - If there is a subclass but there is no parent, an error is still reported, and transformation can be adopted

If the subclass is rewritten, the rewritten shall prevail.

  • Why is the access of member variables and methods different? Because member methods have overrides but member variables do not.
package cn.tedu.oop2;
/*This class is used as an introductory case of polymorphism*/
public class TestDemo {
    public static void main(String[] args) {
        //6. Create "pure" objects for testing
        Animal a = new Animal();
        Cat c = new Cat();
        Dog d = new Dog();
        a.eat();//Small Animal can eat anything ~ it calls the function of the parent class itself
        c.eat();//Kittens like to eat dried fish ~ what they call is the function rewritten by subclasses
        d.eat();//Dogs love meat and bones ~ what they call is the function after subclass rewriting
        /*2.Parent objects cannot use the unique functions of subclasses*/
        //a.jump();// Report an error. There is no such method in the Animal class
        //a.run();// Report an error. There is no such method in the Animal class
        c.jump();//Kitten Cat jumps high ~, subclasses can call their own functions
        d.run();//Dog is running fast. Subclasses can call their own functions

        //7. Create polymorphic objects for testing
        /*3.Pithy formula 1: parent class reference points to subclass object
        * Explanation: the address value of the created subclass object is saved by the reference type variable of the parent type*/
        Animal a2 = new Cat();//The address value of Cat class object is saved by the parent type variable a2
        Animal a3 = new Dog();//The address value of the Dog class object is given to the parent type variable a3 to save
        //8. Test polymorphic objects
        /*4.Pithy formula 2: compile to the left, run to the right
        * Explanation: this method must be defined in the parent class before you can compile and regard the polymorphic object as the parent type
        *      This method must be overridden in subclasses to meet polymorphism. Subclasses are the actual work*/
        a2.eat();//Kittens like to eat dried fish ~, polymorphic objects use the definition of the parent class and the method body of the child class
    }
}
/*1.The premise of polymorphism: inheritance + rewriting*/
//1. Create a parent class
class Animal{
    //3. Common methods for creating parent classes
    public void eat(){
        System.out.println("Small animals Animal Eat anything~");
    }
}
//2.1 create subclass 1
class Cat extends Animal{
    //4.1 method of adding and rewriting
    public void eat(){
        System.out.println("Kittens like to eat dried fish~");
    }
    //5.1 add special functions of subclasses
    public void jump(){
        System.out.println("kitten Cat Jump high~");
    }
}
//2.2 create subclass 2
class Dog extends Animal{
    //4.2 adding and rewriting methods
    @Override
    public void eat(){
        System.out.println("Dogs love meat and bones~");
    }
    //5.2 add special functions of subclasses
    public void run(){
        System.out.println("puppy Dog Run fast~");
    }
}

Polymorphic transformation

Upward transformation

A parent class reference points to a child class object
Class A is the parent class of class B. assign the reference of subclass object B to parent object a, and object B is called the upper transformation object of object a.

  • Format: parent class name object name =new subclass class name.
  • Upward transformation is to directly assign the subclass object to the parent class reference without forced conversion.
  • Using up transformation, you can call all members in the parent class type, but not the unique members in the subclass type. If a subclass overrides an instance method of the parent class, when the instance method is called with the up transformation object, the instance method overridden by the subclass must be called.
  • When a subclass makes an upward transformation, it loses the right to call methods that do not exist in the parent class and can only call methods that exist in the parent class,
class  Person{
	public int x=10;
	public void show() {
		System.out.println("Person of show");
	}
}
class Student extends Person{
	public int y=20;  //Newly defined member variables
	public void print() { //New member method
		System.out.println("Student of print");
	}
	public void show() { //Override parent method
		System.out.println("Student of show");
	}
}
public class Demo {
	public static void main(String []args) {
		Person per= new Student();  //Automatically convert Student object to Person object
		System.out.println(per.y);  //Cannot access new member variables
		System.out.println(per.x);
		per.print(); //Cannot access the new member method
		per.show();  //Access the show method overridden by subclasses
	}
}

Downward transformation


Subclass object points to parent class reference

  • Forced type conversion is required for downward transformation
    Format: a a = new b(); B b= (B) a; // Forced downward transformation

Class A is the parent class of class B. assign the reference of parent object a to child object B, and object a is the lower transformation object of object B.
Parent p = new Child();// In this case, P is the parent type

Tags: Java servlet programming language

Posted by zz50 on Tue, 09 Aug 2022 21:33:18 +0300