JAVA object oriented programming (in)

Posted by gbow on Tue, 04 Jan 2022 13:58:40 +0100

JAVA object oriented programming (middle) (3)

The second and third characteristics of oop: Inheritance and polymorphism

3, The second feature of object-oriented: Inheritance

1. Inherited benefits:

① Reduced code redundancy

② Convenient for function expansion

③ It provides the premise for the later use of polymorphism

2. Inherited format: Class A extensions B {}

​ A: Subclass, derived class, subclass

​ B: Parent class, superclass, base class, superclass

① Embodiment: once subclass A inherits parent class B, subclass A obtains all the attributes and methods declared in parent class B.

​ In particular, for properties and methods declared as private in the parent class, after the child class inherits the parent class, it is still considered to have obtained the private structure in the parent class. Just because of the influence of encapsulation, the child class cannot directly call the structure of the parent class. It can be called with the get and set methods of the parent class

② After the subclass inherits the parent class, it can also declare its own unique properties and methods to expand its functions. The relationship between subclasses and superclasses is different from that between subsets and collections.

3. Provisions on inheritance in Java:

① A class can be inherited by multiple subclasses.

② Single inheritance of classes in Java: a class can only have one parent class.

③ Child parent class is a relative concept and can be inherited multiple times.

④ The parent class directly inherited by the child class is called the direct parent class. The parent class of indirect inheritance is called indirect parent class.

⑤ After the child class inherits the parent class, it obtains the properties and methods declared in the direct parent class and all indirect parent classes.

4. ① if we do not explicitly declare the parent class of a class, this class inherits from Java Lang.Object class

② All java classes (except the java.lang.Object class) inherit directly or indirectly from java. Lang Lang.Object class

③ This means that all java classes have java Functions declared by lang.Object class.

Method override

1. Definition:

In the subclass, the methods inherited from the parent class can be modified as needed, which also becomes the reset and overwrite of Fang FA. When the program executes, the methods of the child class override the methods of the parent class.

2. Rules:

​ Method declaration: permission modifier return value type method name (formal parameter list) {}

  1. The method overridden by the subclass must have the same method name and parameter list as the method overridden by the parent class;

  2. The return value of the method overridden by the subclass cannot be greater than the return value type of the method overridden by the parent class method

    ​ If the return value type of the method overridden by the parent class is void, the return value type of the method overridden by the child class can only be void

    ​ If the return value type of the method overridden by the parent class is type A, the return value type of the method overridden by the child class can be class A or a subclass of class A

    ​ If the return value type of the method overridden by the parent class is the basic data type (such as double), the return value type of the method overridden by the child class must be the same

  3. The access permission of the method overridden by the subclass cannot be less than that of the method overridden by the parent class

    Note: subclasses cannot override methods declared as private permissions in the parent class

  1. The exception thrown by a subclass method cannot be greater than the exception of the overridden method of the parent class

3. Requirements:

​ Methods with the same name and parameters in the subclass and parent class must be declared non static (that is, overridden) or static (not overridden) at the same time. Because the static method belongs to a class, the subclass cannot override the method of the parent class.

4. Use of keyword super

  1. super is understood as the of the parent class, which can be used to call the properties, methods and constructors of the parent class
  2. Use of super
    1. We can in subclass methods or constructors. By using the "super. Attribute" or "super Method to explicitly call the properties or methods declared in the parent class. However, generally, we are used to omitting "super."

    2. Under special circumstances, when we define the property of the same name or overwrite the parent class method in the child class and the parent class, if we want to call the properties declared in the parent class or be rewritten in the subclass, we must explicitly use the way of "super. attribute" and "super. method" to declare that we call the properties declared in the parent class or be rewritten.

    3. Can only be written on the first line of the constructor

      Because no matter which constructor is used to create a subclass object, you need to ensure that the parent class is initialized first.

      Purpose: when a subclass inherits from the parent class, it "inherits" the methods of all properties in the parent class. Therefore, it is necessary for the subclass to know how the parent class initializes the object

5. The whole process of subclass object instantiation

  1. From the result: (inheritance)

    After the subclass inherits from the parent class, it obtains the properties or methods declared in the parent class

    If you create an object of a subclass, the properties declared in all the parent classes will be loaded in heap space

  2. In terms of process:

    When we create a subclass object through the subclass constructor, we must call the constructor of the parent class directly or indirectly, and then call the constructor of the parent class of the parent class And so on until Java. Net is called The lang.Object class is the constructor of a null parameter. Because all the parent class structures have been loaded, you can see that there is a parent class structure in memory, and the child class object can consider calling.

    Although the constructor of the parent class is called when creating a subclass object, an object is created from beginning to end, that is, the object of the subclass.

Examples of inheritance:

package com.atguigu.exer2;

/**
 * @Auther: zgq
 * @Date: 2021/10/21 - 10 - 21 -14:33
 * @Description: com.atguigu.exer2
 * @version: 1.0
 *
 */
public class Account {

    private int id;//account number
    private double balance;//balance
    private double annualInterestRate;//Annual interest rate

    public Account(int id,double balance,double annualInterestRate){
        super();//Even if super() is not explicitly written out, the first line of the constructor must have a non explicit one
        this.id = id;
        this.balance = balance;
        this.annualInterestRate = annualInterestRate;
    }

    public int getId() {
        return id;
    }

    public double getBalance() {
        return balance;
    }

    public double getAnnualInterestRate() {
        return annualInterestRate;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }

    //Return monthly interest rate
    public double getMonthlyInterest(){
        return annualInterestRate / 12;
    }

    //Withdraw money
    public void withdraw(double amount){
        if(balance >= amount){
            balance -= amount;
            return;
        }
        System.out.println("Sorry, your credit is running low!");
    }

    //save money
    public void deposit(double amount){
        if(amount > 0){
            balance += amount;
            return;
        }
        System.out.println("Wrong input!");
    }
}
package com.atguigu.exer2;

/**
 * @Auther: zgq
 * @Date: 2021/10/21 - 10 - 21 -14:58
 * @Description: com.atguigu.exer2
 * @version: 1.0
 * Create a subclass of the Account class, CheckAccount represents the overdrawable Account, and define the attribute overdraft to represent the overdrawable limit
 * Override the Account method in the subclass as follows:
 *  If the withdrawal amount is less than the balance, withdraw directly
 *  If the withdrawal amount > balance, calculate the overdraft limit
 *  Judge whether the overdraft is sufficient to cover the overdraft, if possible
 *      Change the account balance to 0 to offset the overdraft amount
 *  If not
 *      Prompt the user to exceed the overdraft limit
 */
public class CheckAccount extends Account{

    //The parent Account class does not define an empty parameter constructor, so an error will be reported (because the default super () is an empty parameter)
    // Solution 1. Define an empty parameter constructor in the parent class
    // Solution 2. Call the parameterized constructor in the parent class. Here, use method 2
    private double overdraft;//Overdraft limit
    public CheckAccount(int id,double balance,double annualInterestRate,double overdraft){
        super(id,balance,annualInterestRate);
        this.overdraft = overdraft;
    }

    public double getOverdraft() {
        return overdraft;
    }

    @Override
    public void withdraw(double amount) {
        //When the balance is sufficient, the balance shall be deducted
        if(getBalance() >= amount){
            //Method 1
            //setBalance(getBalance() - amount);
            //Method 2
            super.withdraw(amount);
        }
        //If the balance is insufficient and the overdraft limit plus the balance is sufficient, the balance shall be deducted and the overdraft limit shall be deducted
        else if((overdraft + getBalance()) >= amount) {
            amount -= getBalance();
            overdraft -= amount;
            super.withdraw(getBalance());
        }
            else{
            System.out.println("Overdraft limit exceeded!");
        }


    }
}
package com.atguigu.exer2;

import com.sun.jmx.snmp.internal.SnmpOutgoingRequest;

/**
 * @Auther: zgq
 * @Date: 2021/10/21 - 10 - 21 -15:34
 * @Description: com.atguigu.exer2
 * @version: 1.0
 * Create a CheckAccount object with an account of 1122, a balance of 2000, an annual interest rate of 4.5% and an overdraft limit of 5000 yuan.
 * Withdraw 5000 yuan by withdraw method, and print the balance and overdraft limit
 * Withdraw 18000 yuan by withdraw method, and print the balance and overdraft limit
 * Withdraw 3000 yuan by withdraw method, and print the balance and overdraft limit
 */
public class CheckAccountTest {
    public static void main(String[] args) {

        CheckAccount acct = new CheckAccount(1122,20000,0.045,5000);

        acct.withdraw(5000);
        System.out.println("The balance is: " + acct.getBalance() + "element\t" + "The overdraft limit is:" + acct.getOverdraft() + "element");
        acct.withdraw(18000);
        System.out.println("The balance is: " + acct.getBalance() + "element\t" + "The overdraft limit is:" + acct.getOverdraft() + "element");
        acct.withdraw(3000);
        System.out.println("The balance is: " + acct.getBalance() + "element\t" + "The overdraft limit is:" + acct.getOverdraft() + "element");

    }
}

4, The third feature of object-oriented: polymorphism

1. Understanding polymorphism:

It can be understood as multiple forms of a thing.

2. What is polymorphism

Object polymorphism: the reference of the parent class points to the object of the child class (the reference assigned to the parent class by the object of the child class)

Example 1:

   Person p1 = new Men();//Parent class Person, child class Men

3. Use of polymorphism: virtual method call

  1. With the polymorphism of the object, we can only call the methods declared in the parent class at compile time (note that the attribute is not mentioned at this time), but at run time, we actually execute the methods of the child class overriding the parent class.
  2. Summary: compile and look at the Person on the left; Run, look at the right (Men).
  3. Taking example 1 as an example, p1 can only call the methods existing in the parent class Person, but the unique methods in Men cannot be called, but the actual running method is the overridden method in the subclass.

4. Premise of polymorphism:

① Class inheritance ② method rewriting

5. Object polymorphism is only applicable to methods, not attributes (see the left for compilation and operation)

​ Taking example 1 as an example, the attribute ID in the Person class is = 1; The attribute id=2 in the Men class, when we call p1. in the test class ID, the value of the object should be the value 1 of ID in the Person class, not the value 2 in the subclass.

The difference between overloading and rewriting

Use of instanceof keyword and downward transformation

When we use the polymorphism of objects, the memory actually loads the properties and methods specific to subclasses. However, because variables are declared as parent types, only the methods declared in the parent class can be called during compilation, and the properties and methods specific to subclasses cannot be called.

So how can we use the properties and methods unique to subclasses?

Here, you need to use the forced type converter, that is, downward transformation.

Take example 1:

	Man m2 = (Man)p1;

Strongly convert p1 to Man and assign the address to m2. At this time, p2 can call the unique attributes and methods in the subclass Man.

Downward transformation can only convert a parent class to a child class. If there is no child parent relationship between the two classes or if a child class is forcibly converted to a parent class, an exception of ClassCastException will occur at runtime.

For example:

	Woman w3 = (Woman)p1;

Use of instanceof

a instanceof A: judge whether object a is an instance of class A. If yes, return true; otherwise, return false.

Usage scenario: in order to avoid the exception of ClassCastException during the downward transformation, we first judge the instanceof before the downward transformation, and once we return to true, we will carry out the downward transformation; Return false without downward transformation.

If a instanceof A returns true and class B is the parent of class A, a instanceof B also returns true.

Polymorphism example 1:

package com.atguigu.exer3;

/**
 * @Auther: zgq
 * @Date: 2021/10/22 - 10 - 22 -14:58
 * @Description: com.atguigu.exer3
 * @version: 1.0
 * 1,If a subclass overrides the method of the parent class, it means that the method defined in the subclass is completely overridden
 * If the method with the same name of the parent class instance is, it is impossible for the system to transfer the method in the parent class to the child class. (see the left for compilation and the right for operation)
 * 2,For instance variables, there is no such phenomenon, even if the child class is defined to be complete with the parent class
 * With the same instance variable, it is still impossible for this instance variable to override the instance variable defined in the parent class. (see the left for compilation and operation)
 */
public class FieldMethodTest {
    public static void main(String[] args) {
        Sub s = new Sub();
        System.out.println(s.count);//20
        s.display();//20
        Base b = s;
        System.out.println(b == s);//The address values are consistent
        System.out.println(b.count);//10. Polymorphism is only applicable to methods, not attributes
        b.display();//20
    }
}

class Base{
    int count = 10;
    public void display(){
        System.out.println(this.count);
    }
}

class Sub extends Base{
    int count = 20;
    public void display(){
        System.out.println(this.count);
    }
}

Example 2 of polymorphism:

public class InterviewTest {
    public static void main(String[] args) {
        Base1 base = new Sub1();
        base.add(1,2,3);//Sub_1

        Sub1 s = (Sub1)base;
        s.add(1,2,3);//Sub_2
    }
}

class Base1{
    public void add(int a, int... arr){
        System.out.println("Base1");
    }
}
class Sub1 extends Base1{
    public void add(int a, int[] arr){//int[] arr and int Arr is the same, all constitute rewriting
        System.out.println("Sub_1");
    }
    public void add(int a, int b, int c){//And int Arr does not constitute an override
        System.out.println("Sub_2");
    }
}

Topics: JavaSE