JavaSE foundation day10 polymorphism, abstract class / method and interface

 

I Polymorphism

(1) Polymorphism overview

1. Many forms of things are polymorphic

Polymorphism in java is understood as the embodiment of different data types of objects, that is, subclass objects act as parent type objects

 

2. Premise of polymorphism:

(1) There must be inheritance or implementation relationship

(2) Methodical rewriting

(3) The parent class refers to an object that points to a child class

 

3. Format:

Parent type} variable name = new subclass name (argument);

 

4. Examples:

Design a Person class (representing the parent class)

Teacher class, subclass of Person class

Doctor class, subclass of Person class

 

  class Person{}

  class Teacher extends Person{}

  class Doctor extends Person{}

 

Polymorphic expression:

  Person p; / / reference of parent class

  new Teacher(); // Subclass object

  new Doctor(); // Subclass object

 

  Person p = new Teacher();// Human, can be a teacher object, polymorphic expression

  Person p1 = new Doctor();// Human, can be a doctor object, polymorphic expression

This is a variety of human manifestations

(2) Access principle of member variables in polymorphism

1. Principle:

Compile to the left, run to the left

2. Interpretation:

(1) When compiling, it depends on whether there is a definition of the variable in the type of the reference on the left of [=]. If so, the compilation succeeds. If not, the compilation fails

(2) When running, the variables in the type to the left of the equal sign are also used

 

(3) Access characteristics of member methods in polymorphism

1. Principle:

Compile to the left and run to the right

2. Interpretation:

(1) When compiling, it depends on whether the method is defined in the type of the reference on the left of [=]. If so, the compilation succeeds. If not, the compilation fails.

(2) When running, it depends on how to implement this method in the type of the object on the right of [=]. The final run is the subclass overridden method implementation.

 

(4) Upward and downward transformation

1. Upward Transformation:

Use the reference of the subclass to point to the object of the subclass (normal)

In polymorphism, the reference of the parent class is used to point to the object of the child class (upward transformation)

Essence: it narrows the access scope of the object itself and reduces the access permission (only the content defined in the parent class can be accessed)

 

2. Downward Transformation:

Concept:

Let the parent class reference pointing to the subclass object [restore] to the subclass reference

Format:

Subclass type reference name = (subclass type) reference of parent type;

Essence:

[restore] the original access scope of the subclass type

3. Defect: during downward transformation, it may be converted to the type of other subclasses. The compilation will not report an error, but the type conversion exception will occur at runtime

 

4. Solution:

1) before converting, judge whether the type to be converted is the type before the polymorphic object. Use a keyword instanceof to determine whether the downcast type is its own type

2) format:

The polymorphic object instanceof specifies the data type, and the return value is Boolean data

public class Person {
    String name = "Zhang San";
    public void eat(){
        System.out.println("All humans eat");
    }
}
public class Teacher extends Person{
    // name Attribute and Person Consistent member properties in
    String name = "Miss Xiao Li";
    // sex yes Teacher Unique attribute members in
    String sex = "female";
    @Override
    public void eat(){
        System.out.println("Teachers eat cold skin in the evening");
    }
}
public class Doctor extends Person{
    @Override
    public void eat(){
        System.out.println("The doctor eats vegetables in the evening");
    }
    // Doctor Unique features in
    public void save(){
        System.out.println("Doctors can save lives");
    }
}
public class Test {
    public static void main(String[] args) {
        // 1. Polymorphic expression: A parent class reference points to a child class object
        Person p = new Teacher();
        System.out.println(p);
        // 2. Rules for using member variables in polymorphic expressions: Compile look left, Run left
        System.out.println(p.name);
        // System.out.println(p.sex);
        // 4. Because polymorphic upward transformation expressions can only use members in the parent class, Therefore, downward transformation is needed, Restore the parent class reference to the subclass type itself
        // You can call the unique functions and members in the subclass
        Teacher t = (Teacher)p;
        System.out.println(t + "------");
        System.out.println(t.sex);// female

        p.eat();

        Person p1 = new Doctor();
        // 3. Rules for using member methods in polymorphic expressions: Compile look left, Run right
        p1.eat();
        Doctor d = (Doctor)p1;
        d.save();

        // 5. In the process of polymorphic downward transformation, Transformation errors can occur
        // In order to avoid problems in downward transformation, Keywords can be used  instanceof judge
        // Parent class reference  instanceof  Subclass type : Judge whether the parent class reference can be converted to the corresponding subclass type, if possible, return true; Otherwise return false
        if(p instanceof Doctor){
            Doctor or = (Doctor)p;
            or.save();
        }else {
            System.out.println("Cannot convert");
        }
    }
}

 

4.1 practice

Define human and superhuman, define name attribute and business negotiation function in human and superhuman respectively, rewrite human business negotiation function in superhuman, and finally define unique flying function in superhuman

 

analysis:

1. Define human beings, have the attribute of name, and talk about business functions

2. Define a superhuman with a name (which can be inherited from humans), rewrite the business function, and define a unique flying function in superhuman

3. Define a test class to test the use of the following Superman functions in a polymorphic way

public class Man {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void dealBusiness(){
        System.out.println("Human beings can talk about business");
    }
}
public class SuperMan extends Man{
    @Override
    public void dealBusiness(){
        System.out.println(getName() + "Talking about big business");
    }
    public void fly(){
        System.out.println(getName() + "Flying,Waiting to save people");
    }
}
public class TestMan {
    public static void main(String[] args) {
        Man m = new SuperMan();
        m.setName("Pig man");
        m.dealBusiness();

        if(m instanceof SuperMan){
            SuperMan su = (SuperMan)m;
            su.fly();
        }else {
            System.out.println("Type conversion is not allowed");
        }
    }
}

 

(5) Benefits of polymorphism

1. Improved code scalability (flexibility)

2. In the parameter list of the method, the formal parameter is the reference of the parent type. When calling the method in the future, any subclass object of the parent type can be used as the actual parameter of the method.

3. Not in the parameter list of the method, but in the ordinary method body, using the type of the parent class to point to the object of the child class can also improve the scalability of the code. Objects come from a wide range of sources, not just new (they may also be obtained through reflection, read through files, or transmitted through the network. In the compilation stage of writing code, the specific subclass type of the object cannot be known). It is necessary to use the reference of the parent type to operate objects of unknown subclass types

 

Case: there is a farm (designed as a Farmer). Many animals can be raised in the farm. There is a method function (feed) in the farm, which can output the food that each animal needs to eat according to the type of animals provided

For example: provide Cat type parameters to the feed method, and the method output: Cat eats fish;

Provide the Dog type Dog parameter to the feed method, and the method output: Dog gnawing bone;

Provide the Sheep type sheet parameter to the feed method, and the method output: Sheep eat grass;

        ... There are countless kinds of animals, providing different animal types. The feed method outputs what different animals need to feed

 

analysis:

1. Define a farm class Farmer, in which a method function feed is defined

Public void feed() {/ / parameter list of feed method: an animal is required, which can be any animal

/ / for example, Cat c , or Dog d , or sheet s

/ / Law: all parameters required are common and belong to animals

}

2. After the analysis of 1, we need to define an Animal class. All actual animals should be subclasses of Animal type. Therefore, take the Animal parent class type as the formal parameter of the feed method. When calling the feed method, any subclass of Animal type can be used as the actual parameter of the method

 

 

3. Collection: container with variable length

Collection storage features: only reference data types are stored; All referenced data types can be stored; When storing in the collection container, all reference data types need to be passed in as parameters in the parameter type table, and the parameters are stored in the container;

 

Take the parent class Object of all reference types as the formal parameters of the method

 

public abstract class Animal {
    public abstract void eat();
}
public class Cat extends Animal{
    @Override
    public void eat() {
        System.out.println("Cats eat fish");
    }
}
public class Dog extends Animal{
    @Override
    public void eat() {
        System.out.println("Dogs eat bones");
    }
}
public class Sheep extends Animal{
    @Override
    public void eat() {
        System.out.println("Sheep eat grass");
    }
}
public class Farmer {
    // Use a parent type as feed Formal parameters of method
    // feed When actually called, Any one can be passed Animal Subclass object of
    public void feed(Animal a){// Animal a = new Dog();
        // Animal a = new Sheep();
        // Animal a = new Cat();
        a.eat();
    }

    public void useI(int i){// int i = 15;  int i = 3.14;
        System.out.println(i);
    }
}
public class Test {
    public static void main(String[] args) {
        Farmer f = new Farmer();
        Dog d = new Dog();
        Animal dog = new Dog();
        f.feed(dog);// new Dog();  A dog gnaws at a bone

        Animal sheep = new Sheep();
        f.feed(sheep);// new Sheep();

        f.feed(new Cat());

        int w = 15;
        f.useI(w);// 15
        // f.useI(3.14);
    }
}

 

II Abstract class

(1) Abstract method

1. Abstract method: a method in java that has only a method declaration but no method implementation and is modified by the keyword abstract is an abstract method

2. Format:

The modifier abstract returns the value type and method name (parameter list);

3. Function:

Declaration of methods for extracting different results of the same function

4. Note:

Abstract methods can only be defined in abstract classes and interfaces

 

 

 

(2) Abstract class

1. Abstract class: a class that can define abstract methods is an abstract class.

2. The class modified by the keyword abstract in java is an abstract class

3. Define format:

Modifier abstract class class name{

  }

// Using abstract keywords to decorate classes, This class is an abstract class
public abstract class Animal {
    // Abstract methods can only exist in abstract classes
    public abstract void eat();
}

 

(3) Characteristics of abstract classes

1. Abstract classes and abstract methods need to be decorated with the abstract keyword

Abstract class: public abstract class {}

Abstract method: public abstract void test();

2. Relationship between abstract classes and abstract methods:

The class of the abstract method must be an abstract class

Abstract methods may not always be defined in abstract classes, and there may not be abstract methods in abstract classes

3. Instantiation of abstract classes (creating objects)

Abstract classes cannot be instantiated directly

Define subclasses of abstract classes, create objects from subclasses, and call methods

Note: the meaning of abstract class is to have subclass inheritance and override abstract methods

4. The future of subclasses of abstract classes

In the subclass, rewrite (implement) all the abstract methods of the parent class, and the subclass becomes an ordinary class, which can create objects

In the subclass, if all the abstract methods in the parent class are not implemented, the subclass is still an abstract class, and the subclass needs to be modified with the abstract keyword.

// 2. Abstract classes cannot instantiate objects
// The abstract class waits to be the parent class
public abstract class AbstractClass {
    int i = 10;
    public void fun(){
        System.out.println("Common method fun");
    }
    // 1. Abstract methods cannot run, Because there is no method
    // Existential significance: Define the rules that need to be implemented for subclasses
    public abstract void function();
}

 

// 3. Subclasses of abstract parent classes:
// 1) Subclasses override all abstract methods in the parent class, Then this subclass is an ordinary class, It can be used normally
public class AbstractClassSub1 extends AbstractClass{
    @Override
    public void function(){
        System.out.println("I am the parent class abstract method of subclass override");
    }
 }

 

// Subclasses of abstract classes are the second type: The subclass does not override all the abstract methods in the parent class, Then this subclass is still an abstract class
public abstract class AbatractClassSub2 extends AbstractClass{
  
}

 

public class TestAbstract {
    public static void main(String[] args) {
        // 1. Test abstract classes cannot instantiate objects
        // AbstractClass ac = new AbstractClass();

        // 2. Abstract subclasses can be used normally after overriding all abstract methods
        AbstractClassSub1 acs = new AbstractClassSub1();
        System.out.println(acs.i);
        acs.fun();
        acs.function();

        // AbatractClassSub2 acs2 = new AbatractClassSub2();
        }
    }

 

(4) Members in abstract classes

1. Member variables: you can define variables or constants, but they cannot be abstracted

2. Construction method: Yes

Although an abstract class cannot create an object, it must have subclasses that will access the abstract methods of the parent class.

Whether there is a construction method depends not on whether an object can be created, but on whether member variables can be defined. If you can define member variables, you need to initialize member variables, which is completed by constructing methods.

3. Member method:

It can be either an abstract method: force subclass override

It can also be a non abstract method: it is used to inherit subclasses and improve the reusability of code

public abstract class Demo01_Composition of abstract class members {
    // General class + Abstract method
    private String name;
    /*
        Whether a construction method can be defined in a type has nothing to do with whether the type can create an object; It is related to whether member variables can be defined. If member variables can be defined in the type, construction methods can be defined
     */
    public Demo01_Composition of abstract class members(){

    }

    public Demo01_Composition of abstract class members(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public abstract void fun();
}

 

(5) Employee exercises

Programmer: attribute (name, job number, salary, bonus), behavior (work: Software Development)

Test Engineer: attribute (name, job number, salary), behavior (job: software testing)

Project Manager: attribute (name, job number, salary, bonus), behavior (work: control progress)

Using inheritance thought to realize

 

analysis:

1. The above three classes belong to employees. Therefore, the commonalities of the three classes are extracted from the parent Employee class

Attribute: name, job number, salary

Function: working

public abstract class Employee {
    private String name;
    private String id;
    private double salary;

    public Employee() {
    }

    public Employee(String name, String id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    public abstract void work();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

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

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
public class Programmer extends Employee{
    private double jiangJin;
    public Programmer(){}

    public Programmer(String name, String id, double salary, double jiangJin) {
        super(name, id, salary);
        this.jiangJin = jiangJin;
    }

    public double getJiangJin() {
        return jiangJin;
    }

    public void setJiangJin(double jiangJin) {
        this.jiangJin = jiangJin;
    }

    @Override
    public void work() {
        System.out.println(getName() + "--" + getId() + "--" + getSalary() + "--" + jiangJin + "development");
    }
}

 

public class TestProgrammer extends Employee{
    @Override
    public void work() {
        System.out.println(getName() + "--" + getId() + "--" + getSalary() + "--test");
    }
}
public class Test {
    public static void main(String[] args) {
        Programmer p = new Programmer("Zhang San","zs001",15000,3888);
        p.work();

        TestProgrammer tp = new TestProgrammer();
        tp.setName("Li Si");
        tp.setId("ls007");
        tp.setSalary(13999);

        tp.work();
    }
}

 

III Interface

(1) Interface Overview

1. The interface is a collection of java used to describe a variety of different rules;

2. Rules are abstract methods in java, and interfaces are collections that store different abstract methods

Benefits:

Once the naming rules are defined, [method call] and [method implementation] are separated, which can improve development efficiency and reduce code coupling

3. The keyword interface is used in Java to indicate that the interface and class are of the same level

The source file of the interface is also java files still participate in the compilation, and the compiled files are still bytecode files [. class]

2. Programmer, project manager, unique attribute: bonus

(2) Definition, characteristics and precautions of interface

1. Format:

Modifier {interface interface name {interface content}

 

2. Contents:

Attribute: the member variable in the interface, which is actually a member constant. It is modified by public static final by default (it can be accessed by using the interface name)

Method: jdk1 Before 8, there were only abstract methods, which were modified by public abstract by default

 

3. Precautions:

(1) without a construction method, you cannot directly create an object

(2) the abstract method must be implemented by the class and then called by the object of the class

public interface MyInterface {
    // JDK1.8 And in previous versions: There are only two parts
    // 1. Member constant: All member variables in the interface are actually used public static final Embellished
    // Are these modifiers written in part or not, Will be completed or exist by default
public interface MyInterface {
    // JDK1.8 And in previous versions: There are only two parts
    // 1. Member constant: All member variables in the interface are actually used public static final Embellished
    // Are these modifiers written in part or not, Will be completed or exist by default
    public int W = 99;
    // 2. Abstract method: Default modification of all abstract methods in the interface  public abstract
    public abstract void eat();
    void sleep();
    // 3. There is no constructor in the interface,Because member variables cannot be defined
    // public MyInterface(){}
}
public class TestInterface {
    public static void main(String[] args) {
        System.out.println(MyInterface.W);
        // MyInterface.W = 888;
    }
}

(3) Interface implementation

1. After the interface is written, if the rules in it want to be used, it needs to be rewritten by the class to make the class have the rule function in the interface. In this way, the relationship between the class and the interface will occur. The process of rewriting the interface rules by the class is called implementing the interface

2. Class implementation interface:

Use the keyword implements to connect classes and interfaces

3. Format:

Class} implements interface name 1, interface name 2 {content of class}

4. Implementation class of interface:

Is an abstract class that does not implement all abstract methods in the interface

Is a common class that implements all abstract methods in an interface

5. Single realization:

A class implements the implementation of an interface

Class} implements interface name{

Rewrite all abstract methods in the interface

}

6. Multiple implementations:

A class implements multiple different interfaces at the same time

Class} implements interface name 1, interface name 2 {

1. Rewrite all abstract methods in all interfaces

2. The abstract method declared by the same method in different interfaces only needs to be rewritten once

}

 

Interface sheet implementation

public interface MyInterface {
    // JDK1.8 And in previous versions: There are only two parts
    // 1. Member constant: All member variables in the interface are actually used public static final Embellished
    // Are these modifiers written in part or not, Will be completed or exist by default
    public int W = 99;
    // 2. Abstract method: Default modification of all abstract methods in the interface  public abstract
    public abstract void eat();
    void sleep();
    // 3. There is no constructor in the interface,Because member variables cannot be defined
    // public MyInterface(){}
}
// 1. Generally speaking, Implementation class of interface, name: Interface name + Impl, Relationship between expression and interface, Improve code readability
public class MyInterfaceImpl implements MyInterface{
    @Override
    public void eat() {
        System.out.println("Abstract methods in implemented interfaces eat");
    }

    @Override
    public void sleep(){
        System.out.println("Abstract methods in implemented interfaces sleep");
    }
}
public abstract class MyInterfaceImpl2 implements MyInterface{
}
public class TestInterface {
    public static void main(String[] args) {
        System.out.println(MyInterface.W);
        // MyInterface.W = 888;

        // 1. Test interface cannot instantiate object
        // MyInterface my = new MyInterface();

        // 2. The test rewrites the implementation class use of all abstract method interfaces
        MyInterfaceImpl my = new MyInterfaceImpl();
        System.out.println(MyInterfaceImpl.W);
        my.eat();
        my.sleep();
    }
}
public interface A {
    // A In the interface eat Method and MyInterface In the interface A Consistent method
    public abstract void eat();
}
public class ImplAll implements A,MyInterface{
    @Override
    public void eat() {
        System.out.println("Written from eat");
    }

    @Override
    public void sleep() {
        System.out.println("Rewritten sleep");
    }
}

 

(4) Relationship between classes, classes and interfaces, interfaces and interfaces

1. Class and class

For inherited relationships, use the extends keyword

Single inheritance, multiple inheritance and multi-level inheritance are allowed

2. Classes and interfaces:

To implement the relationship, use the implements keyword

There are single implementation and multiple implementation in java

There is no security risk in multiple implementations: even if the two interfaces have the same method declaration, there is only one implementation in the class

3. On the premise of inheriting a parent class, you can also implement multiple interfaces

Format:

Class subclass class name extends parent class class name implements interface 1, interface 2 {

/ / override all abstract methods in the parent class and all interfaces

}

Note: parent first

4. Interface and interface:

Inheritance relationship, using extensions

You can inherit alone, multiple or multiple levels

Multiple inherited formats:

Interface interface name extends parent interface 1, parent interface 2 {

It is equivalent to inheriting all abstract methods of all parent interfaces

}

 

5. Differences between classes and interfaces (design differences):

Abstract class: defines the inherent attributes and behaviors of things

Interface: defines the behavior of things extended through learning and training

 

Inherit a parent class and implement multiple interface codes at the same time

public interface A {
    public abstract void eat();
}
public interface B {
    void sleep();
}
public class Fu {
    public void eat(){
        System.out.println("fu Class let zi Class meal");
    }
}
public class Zi extends Fu implements A,B{
    @Override
    public void sleep() {
        System.out.println("sleep");
    }
}
public class TestfuAndZi {
    public static void main(String[] args) {
        Zi z = new Zi();
        z.eat();
        z.sleep();
    }
}

Relationship between interfaces

public interface C extends A,B{
    // C Both in the interface A and B All abstract methods in both interfaces
}

 

Added by drayfuss on Tue, 08 Mar 2022 15:24:47 +0200