Java--polymorphism; abstract class; interface

1. Abstract class

1. Abstract class definition

Add the abstract keyword before class

public abstract class AbstractClass

2. Abstract classes cannot be instantiated and objects cannot be created (abstract classes are used to be inherited by subclasses)

3. final and abstract cannot be used together, these two keywords are opposite

4. The subclass of an abstract class can be an abstract class; it can also be a non-abstract class

5. Although the abstract class cannot be instantiated, the abstract class has a construction method, which is used by subclasses

6. There may not be abstract methods in abstract classes, abstract methods must appear in abstract classes

7. Abstract method definition

public abstract void doSome();

8. A non-abstract class that inherits an abstract class must override/rewrite/implement the abstract methods in the abstract class

Not all methods without a method body in Java are abstract methods. There are many methods in the Object class that have no method body and end with ";", but none of them are abstract methods, such as:

public native int hashCode();

The bottom layer of the hashCode() method calls the dynamic link library program written in C++

There is no: abstract in the previous modifier list, there is a native, which means calling the JVM native program

It can be seen from this that abstract classes exist for inheritance . If you define an abstract class but do not inherit it, then it is equivalent to creating this abstract class for nothing, because you cannot use it to do anything. For a parent class, if a certain method of it has no meaning in the parent class, it must be implemented differently according to the actual needs of the subclass 

A class containing abstract methods is called an abstract class, but it does not mean that there can only be abstract methods in an abstract class. It can also have member variables and ordinary member methods just like ordinary classes.

There are three main differences between abstract classes and ordinary classes :

1. The abstract method must be public or protected (because if it is private, it cannot be inherited by subclasses, and subclasses cannot implement the method), and the default is public

2. Abstract classes cannot be used to create objects

3. If a class inherits from an abstract class, the subclass must implement the abstract method of the parent class . If the subclass does not implement the abstract method of the parent class, the subclass must also be defined as an abstract class

In other respects, abstract classes are no different from ordinary classes

2. Interface

(1) Interface Basic Grammar

Interface , English is called  interface , in software engineering, interface generally refers to a method or function called by others, it is an abstraction of behavior

In Java, the form of defining an interface is as follows:

[修饰符列表] interface 接口名{}

like:

public interface TestInterface {
    public void doSome();
}

1. Interface is a "reference data type"

2. The interface is completely abstract

3. The interface supports multiple inheritance

4. There are only constants + abstract methods in the interface

5. All elements in the interface are public modified

6. The public abstract of the abstract method in the interface can be omitted

7. The public static final of the constant in the interface can be omitted

8. Methods in interfaces cannot have method bodies

9. For a non-abstract class, when implementing an interface, all methods in the interface must be implemented

10. A class can implement multiple interfaces

11, extends and implements can coexist, extends first, implements later

12. Using interfaces, you can use polymorphism (parent type references point to subtype objects)

(2) The role of interfaces in development

The role of interfaces in development is similar to the role of polymorphism in development        

多态:面向抽象编程,不要面向具体编程。降低程序的耦合度。提高程序的扩展力
            /*
            public class Master{
                public void feed(Dog d){}
                public void feed(Cat c){}
                //假设又要养其它的宠物,那么这个时候需要再加1个方法。(需要修改代码了)
                //这样扩展力太差了,违背了OCP原则(对扩展开放,对修改关闭。)
            }
            */

            public class Master{
                public void feed(Animal a){
                    // 面向Animal父类编程,父类是比子类更抽象的。
                    //所以我们叫做面向抽象编程,不要面向具体编程。
                    //这样程序的扩展力就强。
                }
            }

"Decoupling", abstract-oriented programming can be understood as: interface-oriented programming

Interface-oriented programming can reduce the coupling degree of the program and improve the scalability of the program; it conforms to the OCP development principle

The use of interfaces is inseparable from the polymorphic mechanism (interface + polymorphism can achieve reduced coupling); interfaces can be decoupled

Any interface has a caller and an implementer; the interface can decouple the caller and the implementer

The caller calls for the interface; the implementer writes the implementation for the interface

Interfaces can contain variables and methods

Note:

(1) Variables in the interface will be implicitly designated as public static final variables (and can only be public static final variables, and a compilation error will be reported if modified with private)

(2) The method in the interface will be implicitly designated as a public abstract method , and it can only be a public abstract method (modified with other keywords, such as private, protected, static, final, etc., will report a compilation error), and the interface in All methods cannot have concrete implementations ( methods in interfaces must be abstract methods )

Interface is an extremely abstract type, which is more "abstract" than abstract class, and generally does not define variables in interfaces

A class conforming to a specific set of interfaces needs to use the implements keyword, the specific format is as follows:

public class TestInterfaceImpl implements TestInterface{
    @Override
    public void doSome() {
        // TODO Auto-generated method stub
    }
}

In the development of large projects, the project is generally separated into modules one by one, and interfaces are used between modules to connect (reduce the degree of coupling)

(3) The difference between abstract class and interface

1. Grammatical difference

1. Abstract classes are semi-abstract; interfaces are completely abstract

2. There are constructors in abstract classes; there are no constructors in interfaces

3. Multiple inheritance is supported between interfaces; only single inheritance between classes

4. A class can implement multiple interfaces at the same time; an abstract class can only inherit one class (single inheritance)

5. Only constants and abstract methods are allowed in the interface

6. Interfaces cannot contain static code blocks and static methods, while abstract classes can have static code blocks and static methods

2. Design difference

(1) An abstract class is an abstraction of a thing, that is, an abstraction of a class, while an interface is an abstraction of behavior. An abstract class abstracts the entire class as a whole, including attributes and behaviors, but an interface abstracts the parts (behaviors) of the class.

For example, airplanes and birds are different things, but they all have one thing in common, that is, they can fly. Then when designing, you can design an airplane as an Airplane-like, and a bird as a Bird-like, but you can’t design the feature of flight as a class, so it’s just a behavioral feature, not an abstract description of a class of things. . At this time, the flight can be designed as an interface Fly, including the method fly( ), and then Airplane and Bird implement the Fly interface according to their own needs. Then as for different types of aircraft, such as fighter jets and civil aircraft, it is enough to directly inherit from Airplane. The same is true for birds. Different types of birds can directly inherit from the Bird class.

It can be seen from here that inheritance is a "whether or not" relationship, while interface implementation is a "whether or not" relationship. If a class inherits a certain abstract class, the subclass must be the type of the abstract class, and the interface implementation is related to whether it has or not, such as whether the bird can fly (or whether it has the characteristic of flying), can fly Then you can implement this interface, if you can’t fly, don’t implement this interface.

(2) The design level is different. As the parent class of many subclasses, the abstract class is a template design. While the interface is a behavior specification, it is a radial design.

For example: template in ppt, if template A is used to design ppt B and ppt C, the common part of ppt B and ppt C is template A, if their common parts need to be changed, only template A needs to be changed, There is no need to make changes to ppt B and ppt C again.

And the radial design, for example, a certain elevator is equipped with some kind of alarm, once the alarm is to be updated, all of them must be updated. That is to say, for an abstract class, if you need to add a new method, you can directly add a specific implementation in the abstract class, and the subclass does not need to be changed; but for the interface, if the interface is changed, all implementations of the interface Classes must be modified accordingly.

parameter abstract class interface
The default method implementation There can be a default method to implement Completely abstract, there is no implementation of the method at all
Method to realize

The subclass uses the extends keyword to inherit the abstract class, if the subclass

If it is not an abstract class, it needs to implement all abstractions in the parent abstract class

Like methods, non-abstract methods in the parent class can be overridden or not

The subclass uses implements to implement the interface, and needs to implement all the methods in the interface
constructor Abstract classes can have constructors (constructors cannot be modified with abstract) Interfaces cannot have constructors
Differences from normal Java classes Normal Java classes can be instantiated, abstract classes cannot be instantiated, see context for other differences Interfaces and normal java classes are different types
access modifier  Abstract methods can be modified with public, protected, default The interface is public by default and cannot be modified with other modifiers
main method There can be a main method in an abstract class, which can be run There cannot be a main method in an interface, so it cannot be run
multiple inheritance An abstract class can inherit a class and implement multiple interfaces An interface can only inherit one or more interfaces
speed Abstract classes are faster than interfaces Interface is slightly slower because it needs to find its methods implemented in the class
add new method If you add a new non-abstract method in an abstract class, you can add it directly, because the non-abstract method does not need to be implemented in the subclass. If it is an abstract method, you need to change the code of the subclass and implement this method As long as a method is added to the interface, the class that implements it will change to implement the newly added method

(4) Application scenarios of abstract classes and interfaces

1. If you have some methods and want some of them to have default implementations, use abstract classes

2. If you want to achieve multiple inheritance, you must use interfaces. Since Java does not support multiple inheritance, subclasses cannot inherit multiple classes, but can implement multiple interfaces. So you can use interfaces to solve (polymorphism)

3. If the basic functions are constantly changing, then you need to use abstract classes. If you keep changing the basic functionality and use the interface, then you need to change all the classes that implement the interface

Three, polymorphism

Object-oriented programming has three characteristics: encapsulation, inheritance, polymorphism

1. Encapsulation hides the internal implementation mechanism of the class, which can change the internal structure of the class without affecting the use, and also protects the data. Its internal details are hidden from the outside world, and only its access methods are exposed to the outside world.

2. Inheritance is to reuse the parent class code. If there is an IS-A relationship between two classes, inheritance can be used. At the same time, inheritance also paved the way for the realization of polymorphism.

3. Polymorphism means that the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable are not determined during programming, but are determined during the running of the program, that is, a reference variable will point to The instance object of which class, and the method implemented in which class the method call issued by the reference variable must be determined during the running of the program.

Because the specific class is determined when the program is running, in this way, without modifying the source program code, the reference variable can be bound to various class implementations, which will cause the specific method called by the reference to change accordingly, that is, not modify The program code can change the specific code bound when the program is running, so that the program can choose multiple running states, which is polymorphism.

1. The premise of polymorphism:

(1) There must be an inheritance or realization relationship

(2) There must be method rewriting

(3) There must be a parent class reference pointing to the subclass object

2. Definition and usage format of polymorphism

定义格式:
    父类类型 变量名 = new 子类类型();

Such as: Animal a=new Cat();

animal

public class Animal {
    public void eat() {
        System.out.println("动物吃东西");
    }
}

Cat class, inherits Animal class

//有继承关系
public class Cat extends Animal{
    //有方法的重写
    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }

    //子类特有方法
    public void catchMouse(){
        System.out.println("猫抓老鼠");
    }
}

Dog class, inherited from Animal class

//有继承关系
public class Dog extends Animal{
    //有方法的重写
    @Override
    public void eat() {
        System.out.println("狗啃骨头");
    }

    //子类特有方法
    public void careHome(){
        System.out.println("狗看家护院");
    }
}

Test code:

public class AnimalDemo {
    public static void main(String[] args) {

        //编译时是Animal类,运行时内存是Cat类
        Animal a = new Cat();//向上转型;父类引用指向子类对象
        a.eat();//输出 “猫吃鱼”
        //a.catchMouse(); //编译错误,a是Animal类,没有catchMouse()方法

        //Exception in thread "main" java.lang.ClassCastException: multiple.Animal cannot be cast to multiple.Cat 
        //此时内存中a是Cat,猫不能强转为狗
        Dog d = (Dog)a;//向下转型;父类引用转为子类对象,转型的是父类引用所指向的那个子类对象
        d.eat();
    }
}

Member access characteristics in polymorphism

1. Member variables:

Compile to see the parent class, run to see the parent class

2. Member method:

Compile to see the parent class, run to see the subclass

Relationships between types and types:

is a (inheritance), has a (association), like a (implementation)

1. is a:
                Cat is a Animal (a cat is an animal)
                can satisfy the expression of is a "inheritance relationship"
                A extends B

2. has a:
                I has a Cat (I have a cat)
                can satisfy the expression of has a relationship "association relationship"
                relationship usually exists in the form of "attribute".
                A{                     B b;                 } 3. like a:                 the expression that can satisfy the like a relationship "implementation relationship"                 The realization relationship is usually: the class implements the interface.                 A implements B





Fourth, the final keyword

1. Final modified classes cannot be inherited

2. The method of final modification cannot be overridden

3. A variable modified by final can only be assigned a value once

4. Once the final modified reference points to an object, it can no longer point to other objects, but the attribute data inside the object pointed to by the reference can be modified

public class FinalTest2 {
    public static void main(String[] args) {

        Person p1 = new Person();
        //可以赋值
        p1.name = "张三111";
        System.out.println(p1.name);

        final Person p2 = new Person();
        p2.name = "李四";
        System.out.println(p2.name);

        p2.name = "张三";
        System.out.println(p2.name);

        //不能编译通过;java: 无法为最终变量p2分配值
        //p2 采用 final 修饰,主要限制了 p2 指向堆区中的地址不能修改(也就是p2 只能指向一个对象)
        //p2 指向的对象的属性是可以修改的
        //p2 = new Person();
    }
}

class Person {
    String name;
}
张三111
李四
张三

5. Instance variables modified by final must be initialized manually, and the system default value cannot be used

6. Final modified instance variables are generally used in conjunction with static and are called constants

public static final double PI = 3.1415926;

7. Final modified variables must be initialized explicitly

// final 修饰的变量必须显示初始化
// Variable 'number' might not have been initialized
//private static final Long number;


int i;
// 局部变量必须初始化,如果不使用可以不初始化
// Variable 'i' might not have been initialized
//System.out.println(i);

8. The construction method cannot be modified by final 

Guess you like

Origin blog.csdn.net/MinggeQingchun/article/details/120733179