day10? Object oriented programming ④

inherit

origin

When there are the same properties and behaviors in multiple classes, extract these contents into a single class, then multiple classes do not need to define these properties and behaviors, as long as they inherit that class. As shown in the figure:

                                        

Among them, multiple classes can be called subclasses, and a single class can be called a parent class, a superclass or a base class. Inheritance describes the relationship between things, which is the relationship of is-a. For example, the rabbit in the picture belongs to the herbivore, and the herbivore belongs to the animal. It can be seen that the parent class is more general and the child class is more specific. Through inheritance, we can form a relationship system among many things.

Why inheritance?

When there are the same properties and behaviors in multiple classes, extract these contents into a single class, then multiple classes do not need to define these properties and behaviors, as long as they inherit that class. Multiple classes here are called subclasses (derived classes), and a single class is called a parent class (base or superclass). It can be understood as: "subclass is a parent class".

Inherited format

By using the extends keyword, you can declare that a subclass inherits another parent class. The definition format is as follows:

                                           

Effect:
  • Inheritance reduces code redundancy and improves code reusability.
  • The emergence of inheritance is more conducive to the expansion of functions.
  • The emergence of inheritance makes the relationship between classes and provides the premise of polymorphism.
Note: do not inherit just to get a function in another class
  • If the child class inherits the parent class, it inherits the methods and properties of the parent class.
  • In a subclass, you can use the methods and properties defined in the parent class, or you can create new data and methods.
  • In Java, the inherited keyword is "extends", that is, the subclass is not a subset of the parent class, but an "extension" of the parent class.
Rules on inheritance:
  • A child class cannot directly access private member variables and methods in the parent class.

                                    

Give an example

Defining parent class

//Defining parent class
public class Creature {

    public void breath() {
        System.out.println("breathing");
    }

}

Defining subclasses

package demo01;

//Subclass inherits parent
public class Person extends Creature {

    String name;
    private int age;

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println("Having dinner");
        sleep();
    }

    private void sleep() {
        System.out.println("Sleep");
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}

Define test class

package demo01;

public class ExtendsTest {
    public static void main(String[] args) {
        //Create a subclass object
        Person p1 = new Person();
        //Call method in subclass
        p1.eat();
        //Call method in parent class
        p1.breath();

        //Create a parent class object, unable to access the properties and methods in the child class
        Creature c = new Creature();


    }
}

matters needing attention:

  • Java only supports single inheritance and multi inheritance, not multi inheritance
  • A subclass can only have one parent
  • A parent class can derive multiple subclasses
class SubDemo extends Demo{ } //ok
class SubDemo extends Demo1,Demo2...//error
  • Children and parents are relative concepts.
  • The parent class directly inherited by a subclass 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
  • If we do not explicitly declare the parent class of a class, the class inherits from the java.lang.Object class
  • All Java classes (except java.lang.Object class) directly or indirectly inherit from java.lang.Object class. This means that all Java classes have the function of java.lang.Object class declaration.

Exercises

Defining parent class

package demo02;

/*
Define a parent ManKind class, including
 Member variables int sex and int salary;
Method void manOrWoman(): display "man" (sex==1) or "woman" (sex==0) according to the value of sex;
Method void employed(): displays "no job" (salary==0) or "job" (salary!=0) based on the value of salary.

 */
public class ManKind {

    private int sex;//Gender
    private int salary;//salary

    public ManKind() {
    }


    public ManKind(int sex, int salary) {
        this.sex = sex;
        this.salary = salary;
    }


    public void manOrWoman(){
        if(sex == 1){
            System.out.println("man");
        }else if(sex == 0){
            System.out.println("woman");
        }
    }

    public void employeed(){

        String jobInfo = (salary == 0)? "no job" : "job";
        System.out.println(jobInfo);
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }


}

Defining subclasses

package demo02;

/*
 *
The definition class Kids inherits ManKind and includes
 Member variable int yearsOld;
Method printAge() prints the value of yearsOld.

 */
public class Kids extends ManKind {
    private int yearsOld;

    public Kids() {
    }

    public Kids(int yearsOld) {
        this.yearsOld = yearsOld;
    }

    public void printAge() {
        System.out.println("I am " + yearsOld + " years old.");

    }

    public int getYearsOld() {
        return yearsOld;
    }

    public void setYearsOld(int yearsOld) {
        this.yearsOld = yearsOld;
    }
}

Define test class

package demo02;

/*
 * Define the class KidsTest, instantiate the object someKid of Kids in the main method of the class, and use the object to access the member variables and methods of its parent class.

 */
public class KidsTest {
    public static void main(String[] args) {
        //Create a subclass object
        Kids someKid = new Kids(12);
        //Call methods of this class
        someKid.printAge();

        //Call the method of the parent class
        someKid.setSalary(0);
        someKid.setSex(1);
        someKid.employeed();
        someKid.manOrWoman();


    }
}

Override / overwrite method

Definition: in a subclass, you can modify the methods inherited from the parent class as needed, also known as method reset and override. When the program executes, the method of the subclass will override the method of the parent class.

Requirement:
  • The method overridden by the subclass must have the same method name and parameter list as the method overridden by the parent class
  • The return value type of the method overridden by a subclass cannot be greater than the return value type of the method overridden by the parent class
  • Methods overridden by subclasses cannot use less access than methods overridden by the parent class
  • A subclass cannot override a method declared private in its parent
  • The exception thrown by a subclass method cannot be greater than that of the overridden method of the parent class
Be careful:
  • A method with the same name and parameter in a subclass and a parent must be declared as either nonstatic (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.

summary

Inherited characteristics -- member variables

When there is a relationship between classes, what effect does the member variables in each class have?

Create parent object

  • Only members of the parent class can be used, and no subclass content can be used

Create a subclass object

  • If there is a member variable with different name in the parent class of a subclass, then we can access it according to the name of the member variable. This class and the member variables inherited from the parent class.
  • If a member variable with the same name appears in the parent of a subclass, there are two ways to access it:
    • Access member variables directly through subclass objects: whoever is on the left side of the equal sign will take precedence, if not, it will look up.
    • Access the member variable indirectly through the member method: whoever the method belongs to will be the first to use it; otherwise, it will be found upward

Characteristics after inheritance -- member method

When there are relationships between classes, what are the effects of member methods in each class?

Create parent object

  • Only members of the parent class can be used, and no subclass content can be used

Create a subclass object

  • If a member method with different name appears in the parent class of a subclass, the call at this time has no effect. When an object calls a method, it will first find out whether there is a corresponding method in the subclass. If there is a method in the subclass, it will execute the method in the subclass. If there is no method in the subclass, it will execute the corresponding method in the parent class.
  • If a member method with the same name appears in the parent class of a subclass, the access is a special case, which is called override. Method overwrite: as like as two peas in the subclass, the same method is applied to the parent class (the return value type, the method name and the parameter list are the same), and the coverage effect will also appear, also known as rewriting or copying. The declaration is unchanged and re implemented.

matters needing attention:

  • No matter it is a member method or a member variable, if it does not all look up to the parent class, it will never look down to the child class.

Give an example

Defining parent class

package demo04;



public class Fu {

    public void methodFu() {
        System.out.println("Parent method execution!");
    }

    public void method() {
        System.out.println("Execution of method with duplicate name of parent class!");
    }

}

Defining subclasses

package demo04;


public class Zi extends Fu {

    public void methodZi() {
        System.out.println("Subclass method execution!");
    }

    public void method() {
        System.out.println("Subclass duplicate method execution!");
    }

}

Define test class

package demo04;


/*
In the inheritance relationship of parent-child classes, create child class objects and access the rules of member methods:
    Whoever the created object is, it will be used first. If not, it will be looked up.

matters needing attention:
No matter it is a member method or a member variable, if it does not all look up to the parent class, it will never look down to the child class.

Override
 Concept: in the inheritance relationship, the name of the method is the same, so is the parameter list.

Override: the name of the method is the same as that of the parameter list. Overwrite.
Overload: the name of the method is the same, and the parameter list is different.

Overriding and rewriting feature of method: if a subclass object is created, the subclass method is preferred.
 */
public class Demo01ExtendsMethod {

    public static void main(String[] args) {
        Zi zi = new Zi();

        zi.methodFu();//Parent method execution!
        zi.methodZi();//Subclass method execution!

        // The new subclass object is created, so the subclass method is preferred
        zi.method();//Subclass duplicate method execution!
    }

}

Application of rewriting

  • Subclasses can define their own behavior as needed. It not only follows the function name of the parent class, but also re implements the parent class method according to the needs of the child class, so as to extend and enhance.

Review permission modifier below

Keyword super

super: represents the storage space identifier of the parent class (which can be understood as the reference of the parent).

There are three ways to use the super keyword:

  • In the member method of a subclass, access the member variable of the parent class. Format: super. Member variable name
  • In the member method of a subclass, access the member method of the parent class. Format: super. Member method name ()
  • In the construction method of the subclass, access the construction method of the parent class. Format: super(...)
Be careful:
  • In particular, when there is a member with the same name in the child parent class, super can be used to indicate that the member in the parent class is called
  • super tracing is not limited to direct parent
  • The usage of super is similar to this. This represents the reference of the object of this class, and super represents the identification of the memory space of the parent class

Give an example

Defining parent class

package demo09;

public class Fu {

    int num = 30;

}

Defining subclasses

package demo09;

public class Zi extends Fu {

    int num = 20;

    public Zi() {
        //In the constructor of this class, access another constructor of this class.
        this(123); // The nonparametric construction of this class calls the parametric construction of this class

    }


    public Zi(int n) {
    }

    public void showNum() {
        int num = 10;
        // Accessing local variables
        System.out.println(num);
        //In the member method of this class, access the member variable of this class.
        System.out.println(this.num); // Member variables in this class
        //In the member method of this class, access the member variable in the parent class
        System.out.println(super.num);
    }

    public void methodA() {
        System.out.println("AAA");
    }

    public void methodB() {
        //In the member method of this class, access another member method of this class.
        this.methodA();
        System.out.println("BBB");
    }

}

Call the constructor of the parent class

  • By default, all constructors in a subclass will access the constructors with empty parameters in the parent class
  • When there is no empty parameter constructor in the parent class, the constructor of the child class must specify to call the corresponding constructor in this class or the parent class through this (parameter list) or super (parameter list) statements. At the same time, only one of the two can be selected, and it must be placed in the first line of the constructor. If the subclass constructor does not explicitly call the constructor of the parent class or this class, and the
  • No constructor without parameters, compilation error
  • super and this construction calls cannot be used at the same time.

The difference between this and super

Instantiation process of subclass object

                

The whole process of subclass object instantiation

  • As a result: (inheritance) after the child class inherits the parent class, it obtains the properties or methods declared in the parent class. Create the object of the subclass, and in the heap space, all the properties declared in the parent class will be loaded.
  • From the process point of view: when we create a subclass object through the constructor of a subclass, we will directly or indirectly call the constructor of its parent class, and then call the constructor of its parent class,... Until we call the constructor of the empty parameter of the java.lang.Object class. Because the structure of all the parent classes has been loaded, you can see that there are structures in the parent class in memory, and the child class object can consider calling.

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

Give an example

Defining subclasses


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();
        this.id = id;
        this.balance = balance;
        this.annualInterestRate = annualInterestRate;
    }

    public int getId() {
        return id;
    }

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

    public double getBalance() {
        return balance;
    }

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

    public double getAnnualInterestRate() {
        return annualInterestRate;
    }

    public void setAnnualInterestRate(double annualInterestRate) {
        this.annualInterestRate = annualInterestRate;
    }
    //Return to 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");
    }
    //Deposit money
    public void deposit (double amount){
        if(amount > 0){
            balance += amount;
        }
    }


}

Defining subclasses

/*
 * Create a subclass of Account class CheckAccount to represent overdraft Account, in which an attribute overdraft is defined to represent overdraft limit.
 * Rewrite the withdraw method in the CheckAccount class. The algorithm is as follows:
		If (withdrawal amount < account balance),
		Direct withdrawal
		If (withdrawal amount > account balance),
		Calculate the amount to be overdrawn
		Determine whether overdraft is enough to meet the overdraft needs, if it can
			Change the account balance to 0 to offset the overdraft amount
		If not
			Prompt the user to exceed the limit of the permeable amount

 *
 *
 */
public class CheckAccount extends Account{

    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;
    }


    public void setOverdraft(double overdraft) {
        this.overdraft = overdraft;
    }


    @Override
    public void withdraw(double amount) {
        if(getBalance() >= amount){//Balance is enough for consumption
//			getBalance() -= amount;
            //Method 1:
//			setBalance(getBalance() - amount);
            //Mode two:
            super.withdraw(amount);
        }else if(overdraft >= amount - getBalance()){//Overdraft limit + balance sufficient consumption

            overdraft -= (amount - getBalance());

            super.withdraw(getBalance());

        }else{
            System.out.println("Exceed overdraft limit!");
        }
    }

}

Define test class

/*
 * Write a user program to test the CheckAccount class.
 * In the user program, create a CheckAccount object with an account number of 1122, a balance of 20000, an annual interest rate of 4.5%, and an overdraft limit of 5000 yuan.
	Withdraw 5000 yuan by using the method of withdraw, and print the account balance and the permeable amount.
	Then withdraw 18000 yuan by using the method of withdraw, and print the account balance and the permeable amount.
	Then use the method of withdraw to withdraw 3000 yuan, and print the account balance and the permeable amount.

 *
 */
public class CheckAccountTest {
    public static void main(String[] args) {
        //Create subclasses
        CheckAccount acct = new CheckAccount(1122, 20000, 0.045, 5000);

        acct.withdraw(5000);
        System.out.println("Your account balance is:" + acct.getBalance());
        System.out.println("Your overdraft limit is:" + acct.getOverdraft());
        acct.withdraw(18000);
        System.out.println("Your account balance is:" + acct.getBalance());
        System.out.println("Your overdraft limit is:" + acct.getOverdraft());
        acct.withdraw(3000);
        System.out.println("Your account balance is:" + acct.getBalance());
        System.out.println("Your overdraft limit is:" + acct.getOverdraft());


    }
}

Object oriented feature three: polymorphism

Summary

  • Polymorphism is the third characteristic of object-oriented after encapsulation and inheritance. In life, for example, the movements of running, kittens, dogs and elephants are different. For example, the movements of flying, insects, birds and airplanes are different. It can be seen that the same behavior, through different things, can reflect different forms. Polymorphism describes such a state.

Definition

  • Polymorphism: refers to the same behavior with multiple different manifestations.

premise

  • Inheritance or implementation
  • Method rewriting [meaning expression: no rewriting, no meaning]
  • The parent class reference points to the child class object format representation

The manifestation of polymorphism

The format of polymorphism:

 

0 original articles published, 7 praised, 6159 visited
Private letter follow

Tags: Java less Attribute

Posted on Sat, 07 Mar 2020 03:37:39 -0500 by ksas025