A. The abstract

  • If the method in the parent class is not sure how to implement the method body, then this should be an abstract method.
  • Animals eat cats eat fish and dogs eat bones
  • Define eat as an abstract method

Abstract class: The class in which the abstract method resides must be abstract. Just write abstract before class

How to use abstract classes and abstract methods,

1. The new abstract class object cannot be created directly

2. A subclass must inherit from the abstract superclass

3. Subclasses must override all abstract methods in their abstract parent class

Override (implementation) : Subclasses remove the abstract keyword of an abstract method and then fill in the method body braces.

4. Create subclass objects to use

public class DemoMain { public static void main(String[] args) { // Abimal animal = new Animal(); Cat Cat = new Cat(); cat.eat(); }} public abstract class Animal {// public abstract void eat(); // This is an abstract method that means to eat somethingnormalMethod}} public class Cat extends Animal {@override public voideat(){
        System.out.println("Cats eat fish!); }}Copy the code

An abstract class does not have to have abstract methods

Just make sure that the class in which the abstract method resides is an abstract class.

1. An abstract class cannot create an object. If an abstract class is created, the compiler will fail to pass the error, and only a non-abstract subclass of the object can be created. The constructor of a subclass has a default super(), which requires access to the superclass constructor. 3. Abstract classes do not necessarily contain abstract methods, but a class with abstract methods must be abstract class understanding: a class that does not contain abstract methods, the purpose is not to let the caller create the class object, usually used in special class structure design. 4. A subclass of an abstract class must override all the methods in its abstract parent class, or the compiler will fail unless the subclass is also an abstract class. After all rewriting, this subclass is now a normal class. Understanding: Classes may contain abstract methods, assuming that they do not override all of them. So it doesn't make sense to call an abstract method after you create an object. 5. Static methods can be used in abstract classes, variables understand: static belongs to the class, class name. The call. It doesn't matter if there's an objectCopy the code

public class DemoMain { public static void main(String[] args) { Zi zi = new Zi(); zi.eat(); }} public abstract class Fu {// abstract class publicFu(){
        System.out.println("Abstract superclass constructor execution"); } public abstract void eat(); } public class Zi extends Fu {publicZi(){ //super(); The Fu without arguments can only be run through the Zi's free super call. Direct new is not allowed. System.out.println("Subclass constructor execution!");
    }
    @Override
    public void eat() {// Implement the abstract method system.out.println ()"Eat dinner!"); }}Copy the code

Final keyword

  • For classes and methods, the abstract and final keywords cannot be used at the same time.

1. The final class

Public final class name {//... } The current class cannot have any subclasses (because it cannot be inherited, i.e. cannot be a parent)Copy the code

2. Final decorates member variables

  • You can only assign once manually or once in the constructor
  • You must ensure that all overloaded constructors ina class end up assigning values to final member variables
  • For example, π = 3.1415926… Final modifier variables are called constants

3. Final modification method

  • Cannot be overridden

Public /*final*/ class final {//1. Final class cannot inherit final int j; //2. Final member variables can only be manually assigned once publicFinal(){//3. Or final member variables are not manually assigned, but can only be assigned once in the constructor j = 999; } public final voidmethod(){
        System.out.println("I'm a final modifier ina parent class."); } public static void main(String[] args) { final int a = 10; /*a = 20; */ final f = new final (); /*f.j = 20; Public class FianalSub extends final {public class FianalSub extends final {public class FianalSub extends final {public class FianalSub extends final {public class FianalSub extends final {public class FianalSub extends final {public class FianalSub extends final { Public final void public final void public final void public final void public final voidmethod(){ }*/ public static void main(String[] args) { Final f = new Final(); f.method(); // Use the method from the parent class}}Copy the code

3. Polymorphism

  • The extends extends or implements implementation is a prerequisite for polymorphism.

1. The concept

  • Denotes the various forms of things
  • Examples: Person class, human representation, engineer, doctor, student…

Animal cat dog snake

  • Definition of polymorphism:

1. The parent class has an inheritance relationship. 2. The parent class needs to override the parent class method

Object name = new Subclass name (); Interface name Object name = new implementation class name (); Public class Demo01Multi {public static void main(String[] args) {foo obj = new Zi(); // The parent class refers to the subclass object obj.method(); Obj. MethodFu (); // Method is a member of the parent class of the subclass. }} public class Fu {public void;}} public class Fu {public voidmethod(){
        System.out.println("Superclass method!!");
    }
    public void methodFu(){
        System.out.println("Superclass-specific methods!");
    }
}
public class Zi extends Fu{
    @Override
    public void method(){// override system.out.println ()"Subclass method!!"); }}Copy the code

2. The use characteristics of member variables in polymorphism

  • 1. Access member variables directly from object names: compile to the left, run to the left, and look up if there is none
  • 2. Access member variables indirectly through member methods: compile to the left, run to the right, and look up if you don’t have one

Public class Demo01MultiField {public static void main(String[] args) {foo obj = new Zi(); System.out.println(obj.num); //10 //System.out.println(obj.age); // System.out.println()"= = = = = = = = = = = = = = = = = = = = = = = = = ="); obj.showNUm(); //10 obj.showNUm(); //20 } } public class Fu { int num = 10; public voidshowNUm(){
        System.out.println(num);
    }
}
public class Zi extends Fu{
    int num = 20;
    int age = 16;
    @Override
    public void showNUm(){ System.out.println(num); }}Copy the code

3. Characteristics of using member methods in polymorphism

  • Compile to the left, run to the right, if not up
public class Demo02MultiMethod { public static void main(String[] args) { Fu obj = new Zi(); // The polymorphic parent class refers to the subclass object obj.method(); MethodFu (); obj. MethodFu (); obj. // obj. MethodZi (); // obj. }} public class Zi extends Fu{int num = 20; int age = 16; public voidmethod (){
        System.out.println("Subclass methods!");
    }
    public void methodZi(){
        System.out.println("Subclass-specific methods!");
    }
}
public class Fu {
    int num = 10;
    public void method (){
        System.out.println("Superclass method!");
    }
    public void methodFu(){
        System.out.println("Superclass-specific methods!"); }}Copy the code

4. The use characteristics of static state in polymorphism

  • Compile to the left, run to the left

public class Test(){ public static void main(String[] args){ Fu f = new Zi(); f.speak(); // Static speak! } } public classFu(){
    public static void speak(){
        sout("Static speak in the parent class!");
    }
}
public class Zi extends Fu(){
    public static void speak(){// static can not inherit, static method of the same name sout()."Static Speak in subclasses!"); }}Copy the code

5. Benefits of using polymorphism

  1. Improved code maintainability (inheritance guarantee)
  2. Improved code extensibility (guaranteed by polymorphism)



Public class Test {public static void main(String[] args) {Juicer j = new Juicer(); Juicer j = new Juicer(); Fruit f1 = new Apple(); j.juicing(f1); // Squeeze the apple juice! Fruit f2 = new Orange(); j.juicing(f2); // Squeeze the orange juice! }} public class Juicer {// Define a Juicer class public void juicing(Fruit Fruit){fruit.flow(); } } public class Fruit { public voidflow}} public class Orange extends Fruit{@override public voidflow() {
        System.out.println("Squeeze the orange juice!");
    }
}
public class Apple extends Fruit{
    @Override
    public void flow() {
        System.out.println("Squeeze the juice out of an apple."); }}Copy the code

6. Up-and-down transition of objects

  • The upward transformation of an object is essentially polymorphic:

Object name = new Subclass name (); Animal animal = new Cat(); Create a subclass object on the right and treat it as its parent. Note: Upward transition must be safe, from small to large. From a small range of cats, up to a larger range of animals. Similar to: double num = 100; Int -> double automatic type conversion. Disadvantages: Once an object is upcast to a parent class, there is no way to invoke the subclass's original content solution: use downcast objects.Copy the code

  • The downward transformation of an object is actually an action of reduction

Format: Subclass name Object name = (subclass name) superclass object; Animal Animal = new Cat(); Animal Animal = new Cat(); // Originally a cat, turned upward into an animal. Cat c = (Cat)animal; // It was a cat, but it has been treated as an animal. You have to make sure that when you create an object, it's a cat, so you can go down and call it a cat. B. If the object was originally created as a cat and now needs to be converted to a dog, an error is reported. Similar to: int num = (int)10.0; Int num = (int)10.5; // No, accuracy lossCopy the code

public class Demo01Main { public static void main(String[] args) { Animal animal = new Cat(); // Left father, right son. Animal.eat (); animal.eat(); // animal.catchmouse (); // animal.catchmouse (); Error writing, compiling the left, the parent class without this method / / downward transition reduction action = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = c = (Cat) animal of the Cat; C.catchmouse (); c.catchmouse (); // Dog d = (Dog)animal; // A cat is a new cat, and a dog is a new cat. Abnormal running Java. Lang. ClassCastException class cast exception}} public abstract class Animal {/ / abstract class public abstract void eat (); } public class extends Animal {public voideat(){
        System.out.println("Cats eat fish.");
    }
    public void catchMouse(){// Subclass-specific system.out.println ()"Cats catch mice.");
    }
}
public class Dog extends Animal {
    @Override
    public void eat (){
        System.out.println("Dogs eat bones.");
    }
    public void watchHouse(){
        System.out.println("The dog watches the house."); }}Copy the code

7. How do I know the object referenced by a parent class? What subclass is this class?

  • Instanceof keyword – Return value type, Boolean
  • Format:

Object name of type Instanceof


public class Demo02Instanceof { public static void main(String[] args) { Animal animal = new Cat(); Animal.eat (); // Animal.eat (); // Want to call subclass-specific methods to transition down.if(animal instanceof Dog) {// Check whether the parent reference is Dog Dog d = (Dog) animal; d.watchHouse(); }if(animal instanceof Cat) {// Check if the parent is Cat Cat c = (Cat) animal; c.catchMouse(); } giveMeAPet(new Dog()); } public static void giveMeAPet(Animal animal) {if(animal instanceof Dog) {// Check whether the parent reference is Dog Dog d = (Dog) animal; d.watchHouse(); }if(animal instanceof Cat) {// Check if the parent is Cat Cat c = (Cat) animal; c.catchMouse(); }}}Copy the code