The way of Java learning week4day1

Move towards the goal of Java programmers!

day15

Object oriented - continued 5

A case of polymorphism - "Confucius pretends to be a father"

In order to deepen the understanding of the characteristics of polymorphic members, we will introduce them in the form of pseudo code.

Background: Confucius is a teacher who specializes in explaining the Analects of Confucius. Confucius' father was a newly laid-off Java programmer. At that time, JavaSE was very popular and many people needed to learn. Confucius' father began to speak JavaSE as a teacher. One day, Confucius' father was invited to give a lecture. Confucius was at home alone. At this time, some people came to learn JavaSE from Confucius' father. Confucius began to pretend to be his father, put on his equipment and stick on his beard. It looked very similar! 1

Pseudo code:

class Confucius father{
    int age = 40;
    //teach function
    public void teach(){
        System.out.println("explain JavaSE");
    }
}

class Confucius extends Confucius father{
    int age = 20;
    @Override
    public void teach(){
        System.out.println("Explain the Analects of Confucius");
    }
    //Unique function
    public void playGame(){
        System.out.println("Can write books");
    }
}

Test the above pseudo code in the test class:

public class Test {
    public static void main(String[] args) {
        Confucius father k1 = new Confucius() ;//Upward transformation
        System.out.println(k1.age);//Compile to the left, run to the left. So the output here is 40
        k1.teach();//Compile to the left and run to the right. The output result is "explaining the Analects", which is exposed as soon as the lecture is given.
        k1.playGame();//This sentence will report an error because it is a unique function of the subclass and cannot be accessed. In order to save memory space, downward transformation is recommended. Casts a reference from a parent class to a reference from a child class
        Confucius k2 = (Confucius) k1;
        k2.playGame();//There will be no error in this writing
    }
}

Polymorphic practice

Exercise: polymorphic version of table lamp

/**
 * Requirements: design a lamp, in which the lamp has the attribute of bulb,
 * There is also the method of turning on the light. Design a bulb class,
 * Light bulbs have lighting methods, including red bulb and green bulb
 * They all inherit a lighting method of the bulb class. Please design a piece of code to make the lamp turn on and light up
 * Red light bubbles emit red light, green light bubbles emit green light! (polymorphic)
 *
 */
//Light bulb
class Buble {
    //Define a lighting method
    public void shine(){
        System.out.println("The light bulb can light up...") ;
    }
}

//Green bulb
class GreenBuble extends Buble {
    @Override
    public void shine() {
        System.out.println("The light bulb can emit green light...");
    }
}

//Table lamp
class Lamp {
    //The table lamp has the attribute of bulb
    private Buble buble ;//Light bulb
    //In this way, turn on the light - the bulb should "light up"
    public void on(Buble buble){
        buble.shine() ;//Call the method of lighting the bulb
    }
}

//Red bulb
class RedBuble extends Buble {
    @Override
    public void shine() {
        System.out.println("The light bulb can glow red...");
    }
}

//Test class
public class Test1 {
    public static void main(String[] args) {
        //Create a table lamp class object
        Lamp lamp = new Lamp() ;
        Buble buble = new RedBuble() ;
        //Call the light on method
        lamp.on(buble) ; 
        
        System.out.println("--------------------------------");
        
        Buble buble2 = new GreenBuble() ;
        lamp.on(buble2);

        System.out.println("--------------------------------");
        //Anonymous object: subclass anonymous object
        lamp.on(new RedBuble());
        lamp.on(new GreenBuble());
    }
}

Exercise: polymorphic version of animals

/**
 * Requirement: define an animal class with a method voice()
 * Define a Cat class to implement the voice method
 * Then add a new animal type: Pig and implement the voice() method.
 * Define a Dog class to implement the voice method
 * Define the getInstance method of a Store class:
 * If the parameter passed in is the string dog, a dog object will be returned;
 * If a pig is passed in, a pig object is returned; Otherwise, a Cat object is returned.
 * 
 */
//Animals
class Animal {
    public void voice(){
        System.out.println("Animals need to make sounds...");
    }
}

//Cats
class Cat extends Animal {
    @Override
    public void voice() {
        System.out.println("The cat meowed...");
    }
}

//Dogs 
class Dog extends Animal {
    @Override
    public void voice() {
        System.out.println("The dog barked");
    }
}

//Pigs
class Pig extends Animal {
    @Override
    public void voice() {
        System.out.println("The pig hummed...");
    }
}

//Pet shop
class Store {
    private Store(){} //The construction method is privatized. The outside world cannot use new, and then add static to the function
    public static Animal getInsance(String type){
        if(type.equals("dog")){
            return  new Dog() ;
        }else if(type.equals("pig")){
            return  new Pig() ;
        }else{
            return  new Cat() ;
        }
    }
}

//Test class
public class Test2 {
    public static void main(String[] args) {
        Animal a = Store.getInsance("pig");//new Pig() ;
        a.voice();
        a = Store.getInsance("cat") ; //new Cat() ;
        a.voice();
        a = Store.getInsance("dog") ; //new Dog() ;
        a.voice();
    }
}

abstract class

Reviewing the previous cases of cats and dogs, they all have parent animals. Animals are a very abstract thing. In the definition, we only know that animals can eat and sleep. But when we talk about an animal, we are talking about the most specific animal. Only when it comes to specific animals can we know what they eat and other living habits.

In our development, we should abstract this general thing. Moreover, their behavior of eating or sleeping should not be reflected in detail. They should just be declared (defined as methods without methods) and let specific things (subclasses) be rewritten!

Abstract method

The method of defining members is the same as before, but there is no method body and {}

Format:

	Permission modifier abstract Return value type method name(parameter list);

Format of abstract class

	abstract class Class name{}

The essence of abstract classes

Once the abstract class and abstract method are defined, you must override all the abstract methods of the parent class when defining the subclass!

Essence: force subclasses to do what they have to do!

Characteristics of abstract classes

Abstract class cannot be instantiated! (cannot create object)

Considerations for abstract classes

  • If there are abstract methods in a class, the class must be defined as an abstract class!
  • Abstract classes do not necessarily have abstract methods, but can also be non abstract methods!
  • Abstract classes cannot be instantiated and need to be instantiated with concrete subclasses
  • If a subclass of an abstract class is an abstract class, it cannot be instantiated. However, there must be a most specific subclass, otherwise defining an abstract class is meaningless!
  • When the subclass overrides the parent method, the access permission must be large enough when defining the subclass method, or it must be consistent with the parent (not lower), otherwise an error will be reported!

Instantiation of abstract classes

Through abstract class polymorphism, the parent class reference points to the child class object. The premise is to have the most specific subclass, such as:

	Fu fu = new Zi() ;

Fu here is an abstract class type.

Member characteristics of abstract classes

  1. Member variable: it can be either a variable or a constant. A variable modified by final cannot be assigned a value.
  2. Member method: it can be either abstract or non abstract
  3. Construction method: there is an inheritance relationship, so it is initialized hierarchically. Let the parent class initialize first, and then the child class initialize again!

Interview question: defining the meaning of abstract classes

Question: if there is no abstract method in a class, what is the meaning of defining this class as an abstract class?

Answer: This is a design level problem. The purpose of defining an abstract class is not to directly let this class create objects, because there are concrete subclasses in the end.

For example, the Calendar class Calendar provided by jdk is an abstract class and cannot create objects. However, Calendar provides static methods, and the return value is itself. So the essence of calling other member methods is to create specific subclass objects.

Exercise: Abstract version of table lamp

/**
 * Requirements: design a lamp, in which the lamp has the attribute of bulb,
 * There is also the method of turning on the light. Design a bulb class,
 * Light bulbs have lighting methods, including red bulb and green bulb
 * They all inherit a lighting method of the bulb class. Please design a piece of code to make the lamp turn on and light up
 * Red light bubbles emit red light, green light bubbles emit green light!
 *
 */

//Light bulb
abstract class Buble {
   public abstract void shine() ;
}

//Green light bulb
class GreenBuble extends Buble {
    @Override
    public void shine() {
        System.out.println("The light bulb can emit green light");
    }
}

//Table lamp
class Lamp {
    private Buble buble ;
    public void on(Buble buble){
        buble.shine() ;
    }
}

//Red light bulb
class RedBuble extends Buble {
    @Override
    public void shine() {
        System.out.println("The light bulb can glow red");
    }
}

//Test class
public class Test {
    public static void main(String[] args) {
        //Create a table lamp class object
        Lamp lamp = new Lamp() ;
        Buble buble = new RedBuble() ;//Abstract class polymorphism
        //Call the light on method
        lamp.on(buble) ; 
        System.out.println("--------------------------------");
        
        Buble buble2 = new GreenBuble() ;
        lamp.on(buble2);

        System.out.println("--------------------------------");
        //Anonymous object: subclass anonymous object
        lamp.on(new RedBuble());
        lamp.on(new GreenBuble());
    }
}

Interview question: what keywords cannot abstract conflict with

abstract application scenario: decorating class or member methods

Note when decorating member methods:

  • Abstract cannot be used with the private keyword. Because the member modified by private can only be accessed in the current class, after adding abstract, you need to let the subclass implement this method. This is beyond the scope of the current access, so this is a conflict.

  • Abstract cannot be used with the final keyword. Because the member method modified by final cannot be overridden, and the abstract method modified by abstract needs to be forcibly overridden by subclasses, this is a conflict.

  • Abstract cannot be used with static keyword. Because the method modified by static is related to the class, it will be loaded with the loading of the class after modification. Abstract methods need to be rewritten by subclasses, and finally objects need to be used to realize abstract class polymorphism. Abstract and static use abstract methods together, and there is no method body in the parent class, so loading into memory is meaningless. So this is a conflict.

//Define an abstract method
    //private abstract  void show() ;// Illegal format requires subclasses to implement the show method, while private modified methods can only be accessed at the current time
    //public final abstract void show() ;// Illegal format
    //public static abstract  void show() ; // Illegal format

    //Standard format
    public abstract Return value type method name(parameter list);//Parameter list may be empty / with parameters (basic type / reference type)

Exercise: Abstract version of animal class

/**
 * Requirement: define an animal class with a method voice(),
 * Define a Cat class to implement the voice method
 * Then add a new animal type: Pig and implement the voice() method.
 * Define a Dog class to implement the voice method
 * Define the getInstance method of a Store class:
 * If the parameter passed in is the string dog, a dog object will be returned;
 * If a pig is passed in, a pig object is returned; Otherwise, a Cat object is returned.
 */

//Animals
abstract class Animal { //This animal class -- abstract class
    //optimization
    //Animals need to sound. voice method should only be declared. Subclasses need to implement the method of sound
    public abstract  void voice() ;
}

//Cats
class Cat extends Animal {
    @Override
    public void voice() {
        System.out.println("The cat meowed...");
    }
}

//Dogs 
class Dog extends Animal {
    @Override
    public void voice() {
        System.out.println("The dog barked");
    }
}

//Pigs
class Pig extends Animal {
    @Override
    public void voice() {
        System.out.println("The pig hummed...");
    }
}

//pet shop
class Store {
    private Store(){} //The construction method is privatized. The outside world cannot use new, and then add static to the function
    public static Animal getInsance(String type){
        if(type.equals("dog")){
            return  new Dog() ;
        }else if(type.equals("pig")){
            return  new Pig() ;
        }else{
            return  new Cat() ;
        }
    }
}

//Test class
public class Test {
    public static void main(String[] args) {
        Animal a = Store.getInsance("pig");//new Pig() ;
        a.voice();
        a = Store.getInsance("cat") ; //new Cat() ;
        a.voice();
        a = Store.getInsance("dog") ; //new Dog() ;
        a.voice();
    }
}

Exercise: Abstract version of cat and dog case

/**
 * Requirements: use abstract classes to implement the case of "cat and dog"
 * Define an Animal. The attributes include name, age and color. The behaviors include eating and sleeping
 * Redefine Cat and Dog, both of which inherit the automatic object class
 * Cats and dogs eat differently. Rewrite their methods
 * The cat has special functions: playing with wool; Dogs have a special function: guarding the door 
 */

//Animals
abstract class Animal { //abstract class
    //Name, age, color
    private String name ;
    private int age ;
    private String color ;

    //Nonparametric construction method
    public Animal() {
    }
    //Parametric construction method
    public Animal(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }
    //Public access method
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    //Animal eating and sleeping should be declared - abstract method
    public abstract  String eat() ;
    public abstract  void sleep() ;
}

//Cats
class Cat extends Animal {
    //Construction method
    public Cat() {
    }
    public Cat(String name, int age, String color) {
        super(name, age, color);
    }
    @Override
    public String eat() {
        return "Cats eat fish...";
    }
    @Override
    public void sleep() {
        System.out.println("The cat licked its paws to sleep...");
    }
    //Unique function
    public void playGame() {
        System.out.println("Cats can play with wool...");
    }
}

//Dogs 
class Dog extends Animal {
    //Construction method
    public Dog() {
    }
    public Dog(String name, int age, String color) {
        super(name, age, color);
    }
    @Override
    public String eat() {
        return "Dogs eat bones";
    }
    @Override
    public void sleep() {
        System.out.println("The dog slept on its stomach...");
    }
    //Unique function
    public void catchRabit(){
        System.out.println(this.getName()+"Can catch rabbits");
    }
}

public class Test {
    public static void main(String[] args) {
        //Test class
        //Method 1: parameterless construction + setXXX()/getXXX()
        //Polymorphism test
        Animal a = new Dog() ;//Abstract class polymorphism
        String result = a.eat();
        a.setName("sunspot") ;
        a.setAge(3) ;
        a.setColor("brown") ;
        System.out.println(a.getName()+"---"+a.getAge()+"---"+a.getColor());
        System.out.println(result);
        a.sleep(); ;
        //Unique function
        //Downward transformation
        Dog d = (Dog) a;
        d.catchRabit() ;

        System.out.println("--------------------------------------") ;
        
        //Method 2: parameter construction method + getXXX()
        //Cat test
        Animal a3 = new Cat("Orange cat", 3, "Decor");
        System.out.println(a3.getName()+"---"+a3.getAge()+"---"
                +a3.getColor());
        String str2 = a3.eat();
        System.out.println(str2);
        a3.sleep();
        Cat cc = (Cat) a3;
        cc.playGame();
    }
}

Interface

Going back to the example of cats and dogs, cats and dogs are a kind of animals, but they can have functions that they don't have in themselves, such as high jump, drilling fire circles and doing math problems. This is after the day after tomorrow's learning and training of trainers, they have these additional functions. Through this example, we can conclude that if an object realizes additional functions, it also has this function.

Back in Java, the definition of interface is very similar to the summary above. Interface is a specification. If a class can implement additional functions in the interface, it means that the current class has this function. From a macro perspective, interfaces allow things to achieve additional functions. An interface is a type that is more abstract than an abstract class.

Format of interface

	public interface Interface name{}

The naming norms of interface name and class name are consistent, and both follow the "big hump naming method"

Class implements the format of the interface

	class Class name implements Interface name{}

Characteristics of interface

  1. Methods in an interface can only be abstract methods and cannot have a method body

  2. Interface cannot be instantiated (object cannot be created)

    Interface instantiation is realized through interface polymorphism

Interface example

/**
 * Two functions are defined in the AnimalArain interface:
 * jump():high jump
 * compute():calculation
 * Finally, write the test class test
 */

interface Jump{
//    public void jump() {/ / methods of the interface can only be abstract methods
//
//    }
   public abstract void jump() ;
}

interface  ComplateCal{//Interface for computing
    public abstract  void cal() ;
}
class Dog{
    public void lookDoor(){
        System.out.println("Dogs can watch the door");
    }
}

//High jump, it's a dog, and then part of the extra function, high jump
class JumpDog extends Dog implements Jump,ComplateCal{ //Multiple interfaces can be implemented while inheriting a class

    @Override
    public void jump() {
        System.out.println("The dog can jump high...");
    }

    @Override
    public void cal() {
        System.out.println("The dog can do calculations...");
    }
}

//Test class
public class InterfaceDemo {
    public static void main(String[] args) {
        //Create interface object
        // Jump jump = new Jump () ;// The interface cannot be instantiated,
        //How to instantiate it: interface polymorphism - providing sub implementation classes of the interface
        Jump jump = new JumpDog() ;//Interface type ----- > sub implementation class object (interface type)
        jump.jump() ;
        //Downward transformation
        JumpDog jumpDog  = (JumpDog) jump;
        jumpDog.lookDoor() ;
        jumpDog.cal();
        ComplateCal cc = new JumpDog() ;//Interface polymorphism
        cc.cal() ;
    }
}

Interface member characteristics

  • Member variables can only be constants. The default modifier is public static final, which can be omitted
  • There is no construction method, but some abstract methods are provided to let the subclass implement these methods
  • Member methods can only be abstract methods. The default modifier is public abstract and can be omitted

Class to class, class to interface and interface to interface relationship

  • Class to class: inheritance relationship. Only single inheritance is allowed. Multiple inheritance is not supported, but multiple inheritance is allowed

  • Class and interface: implementation relationship, which can be implemented by single (Interface) or multiple (Interface). You can also implement multiple interfaces while inheriting a class

    	class Sub implementation class name extends Parent class name implements Interface 1,Interface 2,...{}
    
  • Interface and interface: inheritance relationship, which can be inherited not only by single inheritance, but also by multiple inheritance or multiple inheritance

Interview question: what is the difference between an interface and an abstract class

  1. Differences in membership

    • Members of the interface:

      • Member variable: can only be a constant. There is a default modifier public static final

      In actual development, if you want to customize a constant, you can define an interface first, and then write a constant in it!

      • Member method: Generally speaking, it is an abstract method. It can be a default method or a static method. It must have a method body
      • Construction method: None
    • Members of abstract classes

      • Member variable: it can be either a variable or a constant. A variable modified by final cannot be assigned a value.
      • Member method: it can be either an abstract method or a non abstract method. If it is an abstract method, the abstract in the method cannot be omitted.
      • Construction method: it can be constructed with or without parameters. Because it is an inheritance relationship, it must be initialized hierarchically.
  2. Relationship differences

    • Class to class relationship: inheritance relationship

      Classes can be abstract or concrete. Inheritance relationships only support single inheritance, not multiple inheritance. You can inherit multiple layers

    • Relationship between class and interface: implementation relationship

      A class can implement multiple interfaces while inheriting another class

    • Interface to interface relationship: inheritance relationship

      You can inherit single, multiple, or multiple levels

  3. Differences in design concepts

    • Abstract classes must eventually have specific subclasses, which are inheritance relationships, reflecting an "is a" relationship, which can be described by abstract class polymorphism

    • The interface describes the functions that things do not have. It is an additional expansion function cultivated through background learning.

      The core idea of the interface embodies the relationship of "like a"

Exercise: athletes and coaches

analysis:

realization:

//Basketball coach
class BasketballCoach extends Coach{
    public BasketballCoach() {
    }
    public BasketballCoach(String name, int age, String gender) {
        super(name, age, gender);
    }
    @Override
    public void teach() {
        System.out.println("The basketball coach taught the players how to dribble");
    }
}

//Basketball players
class BasketBallPlayer extends Player {
    public BasketBallPlayer() {
    }
    public BasketBallPlayer(String name, int age, String gender) {
        super(name, age, gender);
    }
    @Override
    public void study() {
        System.out.println("Basketball players learn how to dribble and shoot");
    }
}

//Coach class
abstract class Coach extends Person{
    public Coach() {
    }
    public Coach(String name, int age, String gender) {
        super(name, age, gender);
    }
    @Override
    public void eat() {
        System.out.println("The coach ate fast food");
    }
    public abstract void teach();
}

//human beings
public abstract class Person { //abstract class
    private String name ;    //full name
    private int age ;    //Age
    private String gender ;    //Gender

    //No reference
    public Person() {
    }
    //Parametric structure
    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    //Public access method
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    //The food is different, so let the subclass implement and just give the declaration
    public abstract  void eat() ;
}

//Table tennis coach
class PingPangCoach extends Coach implements SpeakEnglish{
    public PingPangCoach() {
    }
    public PingPangCoach(String name, int age, String gender) {
        super(name, age, gender);
    }
    @Override
    public void teach() {
        System.out.println("Table tennis coaches teach players how to play");
    }
    @Override
    public void speak() {
        System.out.println("The table tennis coach can speak English!");
    }
}

//Table tennis players
class PingPangPlayer extends Player implements SpeakEnglish {
    public PingPangPlayer() {
    }
    public PingPangPlayer(String name, int age, String gender) {
        super(name, age, gender);
    }
    @Override
    public void study() {
        System.out.println("Table tennis players learn how to serve and receive the ball");
    }
    @Override
    public void speak() {
        System.out.println("Table tennis players can speak English!");
    }
}

//Athletes
abstract class Player extends  Person { //abstract class
    //Construction method
    public Player() {
    }
    public Player(String name, int age, String gender) {
        super(name, age, gender);
    }
    @Override
    public void eat() {
        System.out.println("Athletes eat nutritious meals");
    }
    //The content of learning is different. Only when you see specific athletes can you know what you are learning
    //Learning function - just give a statement
    public abstract  void study() ;
}

//English speaking interface
interface SpeakEnglish {
    //Speak English
    public abstract void speak() ;
}

//Test class
public class Test {
    public static void main(String[] args) {
        SpeakEnglish se = new PingPangPlayer() ;
        se.speak(); //Can speak English
        PingPangPlayer pingPangPlayer = (PingPangPlayer)se;
        pingPangPlayer.setName("Malone") ;
        pingPangPlayer.setAge(30) ;
        pingPangPlayer.setGender("male");
        System.out.println(pingPangPlayer.getName()+"---"+pingPangPlayer.getAge()+"---"+pingPangPlayer.getGender()) ;
        pingPangPlayer.eat() ;
        pingPangPlayer.study();
        
        System.out.println("--------------------------------------") ;
        
        Coach pc = new PingPangCoach("Liu Guoliang",40,"male");
        PingPangCoach pingPangCoach = (PingPangCoach) pc;
        pingPangCoach.speak();
        System.out.println(pc.getName()+"---"+pc.getAge()+"---"+pc.getGender());
        pc.eat();
        pc.teach();
    }
}

Blogs inevitably make some mistakes. If there is any problem with the writing, you are welcome to criticize and correct.

  1. The story is completely fictional. ↩︎

Keywords: Java

Added by Niccaman on Wed, 26 Jan 2022 03:43:13 +0200