Polymorphism-abstract class-interface

Posted by EvoDan on Thu, 15 Aug 2019 13:06:36 +0200

1. Polymorphism

Overview of 1.1 Polymorphism (Memory)

  • What is polymorphism

    Different forms of the same object at different times

  • The premise of polymorphism

    • Inheritance or realization of the relationship
    • Rewrite methodologically
    • Have parent references pointing to child class objects

Membership Access Characteristics in 1.2 Polymorphism (Memory)

  • Membership access characteristics

    • Membership variables

      Compiling looks at the parent class and running looks at the parent class

    • Membership method

      Compile to see parent class, run to see subclass

  • Code demonstration

    • Animals

      public class Animal {
          public int age = 40;
      
          public void eat() {
              System.out.println("Animals eat");
          }
      }
      
    • Feline

      public class Cat extends Animal {
          public int age = 20;
          public int weight = 10;
      
          @Override
          public void eat() {
              System.out.println("Cats eat fish");
          }
      
          public void playGame() {
              System.out.println("Cat hide-and-seek");
          }
      }
      
    • Test class

      public class AnimalDemo {
          public static void main(String[] args) {
              //There are parent references pointing to subclass objects
              Animal a = new Cat();
      
              System.out.println(a.age);
      //        System.out.println(a.weight);
      
              a.eat();
      //        a.playGame();
          }
      }
      

1.3 Benefits and Disadvantages of Polymorphism (Memory)

  • benefit

    Improve the extensibility of the program. When defining a method, the parent type is used as a parameter, and when using it, specific subtypes are used to participate in the operation.

  • malpractice

    Special members of subclasses cannot be used

Transition in 1.4 Polymorphism (Application)

  • Upward transformation

    Parent references to subclass objects are upward transitions

  • Downward transition

    Format: Subtype object name = (subtype) parent reference;

  • Code demonstration

    • Animals
    public class Animal {
        public void eat() {
            System.out.println("Animals eat");
        }
    }
    
    • Feline
    public class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    
        public void playGame() {
            System.out.println("Cat hide-and-seek");
        }
    }
    
    • Test class
    public class AnimalDemo {
        public static void main(String[] args) {
            //polymorphic
            //Upward transformation
            Animal a = new Cat();
            a.eat();
    //      a.playGame();
    
    
            //Downward transition
            Cat c = (Cat)a;
            c.eat();
            c.playGame();
        }
    }
    

1.5 polymorphism case (application)

  • Case requirements

    Use the idea of polymorphism to implement cat and dog cases and test them in the test class.

  • code implementation

    • Animals
    public class Animal {
        private String name;
        private int age;
    
        public Animal() {
        }
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public void eat() {
            System.out.println("Animals eat");
        }
    }
    
    • Feline
    public class Cat extends Animal {
    
        public Cat() {
        }
    
        public Cat(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    
    • Dogs
    public class Dog extends Animal {
    
        public Dog() {
        }
    
        public Dog(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println("Dogs eat bones");
        }
    }
    
    • Test class
    public class AnimalDemo {
        public static void main(String[] args) {
            //Create cat objects for testing
            Animal a = new Cat();
            a.setName("Garfield");
            a.setAge(5);
            System.out.println(a.getName() + "," + a.getAge());
            a.eat();
    
            a = new Cat("Garfield", 5);
            System.out.println(a.getName() + "," + a.getAge());
            a.eat();
        }
    }
    

2. abstract classes

2.1 Overview of abstract classes (understanding)

When we extract common functions of subclasses, some methods are not embodied in the parent class, so we need abstract classes at this time.

In Java, a method without a method body should be defined as an abstract method, and if there is an abstract method in a class, it must be defined as an abstract class!

2.2 Characteristics of abstract classes (memory)

  • Abstract classes and abstract methods must be modified with abstract keywords

    //Definition of abstract class
    public abstract class Class name {}
    
    //Definition of abstract method
    public abstract void eat();
    
  • There must be no abstract method in abstract class, and the class with abstract method must be abstract class.

  • Abstract classes cannot be instantiated

    How do abstract classes be instantiated? Referring to polymorphism, we instantiate subclass objects, which is called abstract class polymorphism.

  • Subclasses of abstract classes

    Either override all abstract methods in abstract classes

    Or abstract classes

2.3 Membership characteristics of abstract classes (memory)

  • Membership characteristics

    • Membership variables
      • They can be variables.
      • It can also be a constant.
    • Construction method
      • Empty parametric structure
      • Parametric structure
    • Membership method
      • Abstract method
      • General method
  • Code demonstration

    • Animals
    public abstract class Animal {
    
        private int age = 20;
        private final String city = "Beijing";
    
        public Animal() {}
    
        public Animal(int age) {
            this.age = age;
        }
    
    
        public void show() {
            age = 40;
            System.out.println(age);
    //        city = Shanghai;
            System.out.println(city);
        }
    
        public abstract void eat();
    
    }
    
    • Feline
    public class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    
    • Test class
    public class AnimalDemo {
        public static void main(String[] args) {
            Animal a = new Cat();
            a.eat();
            a.show();
        }
    }
    

2.4 Cases of abstract classes (applications)

  • Case requirements

    Use the idea of abstract classes to implement cat and dog cases and test them in test classes.

  • code implementation

    • Animals
    public abstract class Animal {
        private String name;
        private int age;
    
        public Animal() {
        }
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public abstract void eat();
    }
    
    • Feline
    public class Cat extends Animal {
    
        public Cat() {
        }
    
        public Cat(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    
    • Dogs
    public class Dog extends Animal {
    
        public Dog() {
        }
    
        public Dog(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println("Dogs eat bones");
        }
    }
    
    • Test class
    public class AnimalDemo {
        public static void main(String[] args) {
            //Create objects in a polymorphic manner
            Animal a = new Cat();
            a.setName("Garfield");
            a.setAge(5);
            System.out.println(a.getName()+","+a.getAge());
            a.eat();
            System.out.println("--------");
    
            a = new Cat("Garfield",5);
            System.out.println(a.getName()+","+a.getAge());
            a.eat();
        }
    }
    

3. Interface

3.1 Interface Overview (Understanding)

Interface is a kind of common standard. As long as it meets the standard, everyone can use it.

Interfaces in Java are more embodied in the abstraction of behavior!

Characteristics of 3.2 Interface (Memory)

  • interface Modified with Keyword interface

    public interface interface interface name {} 
    
  • Class Implementation Interface Represented by implements

    public class class name implements interface name {}
    
  • Interfaces cannot be instantiated

    How do interfaces be instantiated? Referring to the way of polymorphism, we can instantiate class objects, which is called interface polymorphism.

    Forms of polymorphism: concrete class polymorphism, abstract class polymorphism, interface polymorphism.

  • Subclasses of interfaces

    Or rewrite all abstract methods in the interface

    Either subclasses or abstract classes

3.3 Interface Membership (Memory)

  • Membership characteristics

    • Membership variables

      It can only be a constant.
      Default modifier: public static final

    • Construction method

      No, because interfaces are mainly extended functions, not specific ones.

    • Membership method

      It can only be an abstract method.

      Default modifier: public abstract

      There are some new features in JDK8 and JDK9 about methods in interfaces, which will be explained later.

  • Code demonstration

    • Interface
    public interface Inter {
        public int num = 10;
        public final int num2 = 20;
    //    public static final int num3 = 30;
        int num3 = 30;
    
    //    public Inter() {}
    
    //    public void show() {}
    
        public abstract void method();
        void show();
    }
    
    • Implementation class
    public class InterImpl extends Object implements Inter {
        public InterImpl() {
            super();
        }
    
        @Override
        public void method() {
            System.out.println("method");
        }
    
        @Override
        public void show() {
            System.out.println("show");
        }
    }
    
    • Test class
    public class InterfaceDemo {
        public static void main(String[] args) {
            Inter i = new InterImpl();
    //        i.num = 20;
            System.out.println(i.num);
    //        i.num2 = 40;
            System.out.println(i.num2);
            System.out.println(Inter.num);
        }
    }
    

3.4 Interface Case (Application)

  • Case requirements

    Training cats and dogs, they can jump high, here add the function of high jump.

    Use abstract classes and interfaces to implement cat and dog cases and test them in test classes.

  • code implementation

    • Animals
    public abstract class Animal {
        private String name;
        private int age;
    
        public Animal() {
        }
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public abstract void eat();
    }
    
    • High Jump Interface
    public interface Jumpping {
        public abstract void jump();
    }
    
    • Feline
    public class Cat extends Animal implements Jumpping {
    
        public Cat() {
        }
    
        public Cat(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    
        @Override
        public void jump() {
            System.out.println("Cats can jump high.");
        }
    }
    
    • Test class
    public class AnimalDemo {
        public static void main(String[] args) {
            //Create objects and call methods
            Jumpping j = new Cat();
            j.jump();
            System.out.println("--------");
    
            Animal a = new Cat();
            a.setName("Garfield");
            a.setAge(5);
            System.out.println(a.getName()+","+a.getAge());
            a.eat();
    //        a.jump();
    
            a = new Cat("Garfield",5);
            System.out.println(a.getName()+","+a.getAge());
            a.eat();
            System.out.println("--------");
    
            Cat c = new Cat();
            c.setName("Garfield");
            c.setAge(5);
            System.out.println(c.getName()+","+c.getAge());
            c.eat();
            c.jump();
        }
    }
    

3.5 Class and Interface Relations (Memory)

  • Relations between Classes and Classes

    Inheritance relationship can only be inherited singly, but it can be inherited at multiple levels.

  • Relations between classes and interfaces

    Implementing relationships can be implemented either singly or in multiple ways. It can also implement multiple interfaces while inheriting a class.

  • The relationship between interface and interface

    Inheritance can be inherited either singly or in multiple ways.

3.6 Differences between abstract classes and interfaces (memory)

  • Membership distinction

    • abstract class

      Variables, constants, constructive methods, abstract methods and non-abstract methods

    • Interface

      Constants; abstract methods

  • Relational distinction

    • Classes and Classes

      Inheritance, single inheritance

    • Classes and interfaces

      Implementing can be implemented either singly or in multiple ways.

    • Interface and Interface

      Inheritance, single inheritance, multiple inheritance

  • The Difference of Design Ideas

    • abstract class

      Class abstraction, including attributes, behavior

    • Interface

      Abstraction of behavior, mainly behavior

4. Comprehensive cases

4.1 Case Requirements (Understanding)

We now have table tennis players and basketball players, table tennis coaches and basketball coaches.

In order to communicate abroad, people related to table tennis need to learn English.

Use what you have learned to analyze the specific classes, abstract classes and interfaces in this case, and implement them in code.

[External Link Picture Transfer Failure (img-C8Jt4SoF-15658664721) (img01.png)]

4.2 Code Implementation (Application)

  • Abstract human
public abstract class Person {
    private String name;
    private int age;

    public Person() {
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public abstract void eat();
}
  • Abstract athlete class
public abstract class Player extends Person {
    public Player() {
    }

    public Player(String name, int age) {
        super(name, age);
    }

    public abstract void study();
}
  • Abstract coaching class
public abstract class Coach extends Person {
    public Coach() {
    }

    public Coach(String name, int age) {
        super(name, age);
    }

    public abstract void teach();
}
  • Learning English Interface
public interface SpeakEnglish {
    public abstract void speak();
}
  • Basketball coach
public class BasketballCoach extends Coach {
    public BasketballCoach() {
    }

    public BasketballCoach(String name, int age) {
        super(name, age);
    }

    @Override
    public void teach() {
        System.out.println("Basketball coaches teach dribbling and shooting");
    }

    @Override
    public void eat() {
        System.out.println("Basketball coaches eat mutton and drink milk");
    }
}
  • Table tennis coach
public class PingPangCoach extends Coach implements SpeakEnglish {

    public PingPangCoach() {
    }

    public PingPangCoach(String name, int age) {
        super(name, age);
    }

    @Override
    public void teach() {
        System.out.println("Table tennis coaches teach how to serve and receive the ball");
    }

    @Override
    public void eat() {
        System.out.println("Table tennis coaches eat cabbage and drink rice porridge");
    }

    @Override
    public void speak() {
        System.out.println("Table tennis coach speaks English");
    }
}
  • Table tennis players
public class PingPangPlayer extends Player implements SpeakEnglish {

    public PingPangPlayer() {
    }

    public PingPangPlayer(String name, int age) {
        super(name, age);
    }

    @Override
    public void study() {
        System.out.println("Table tennis players learn how to serve and receive the ball");
    }

    @Override
    public void eat() {
        System.out.println("Table tennis players eat Chinese cabbage and drink millet porridge");
    }

    @Override
    public void speak() {
        System.out.println("Table Tennis Players Speak English");
    }
}
  • Basketball players
public class BasketballPlayer extends Player {

    public BasketballPlayer() {
    }

    public BasketballPlayer(String name, int age) {
        super(name, age);
    }

    @Override
    public void study() {
        System.out.println("Basketball players learn how to dribble and shoot");
    }

    @Override
    public void eat() {
        System.out.println("Basketball players eat beef and drink milk");
    }
}

`java
public class PingPangPlayer extends Player implements SpeakEnglish {

public PingPangPlayer() {
}

public PingPangPlayer(String name, int age) {
    super(name, age);
}

@Override
public void study() {
    System.out.println("Table tennis players learn how to serve and receive the ball");
}

@Override
public void eat() {
    System.out.println("Table tennis players eat Chinese cabbage and drink millet porridge");
}

@Override
public void speak() {
    System.out.println("Table Tennis Players Speak English");
}

}

- Basketball players

```java
public class BasketballPlayer extends Player {

    public BasketballPlayer() {
    }

    public BasketballPlayer(String name, int age) {
        super(name, age);
    }

    @Override
    public void study() {
        System.out.println("Basketball players learn how to dribble and shoot");
    }

    @Override
    public void eat() {
        System.out.println("Basketball players eat beef and drink milk");
    }
}

Topics: Java