Java study notes (7) - interfaces and polymorphism

Previous say Java object-oriented inheritance, comes in succession: when calling the member variable object, according to the type of reference to decide who to call, when to call a member method and the presence of polymorphisms, specifically who called the new method requires the object out of the decision, this is mainly described in Java interfaces polymorphic and the use of polymorphic form

Polymorphism

At that time when learning C ++, to use polymorphic function needs to be defined as virtual, that is, the virtual function. Class virtual function is present, there is a head pointer object virtual function table, the address table stores virtual function is a virtual function, using a pointer or reference to the parent class may be a function of the address in the virtual function table when to call the method the function is called polymorphic form.

At that time the multi-state has a very refined definition of learning C ++: pointer points to a different base class derived class, different behavior. Here refers to the different behavior when called with a virtual function, the derived class can call different functions. Here we say a few basic conditions polymorphic forms: 1) a pointer or reference type is the base class; 2) need to point to a derived class; 3) function calls the base class must be overridden functions.

public class Parent{
    public void sayHelllo(){
        System.out.println("Hello Parent");
    }

    public void sayHello(String name){
        System.out.println("Hello" + name);
    }
}

public class Child extends Parent{
    public void sayHello(){
        System.out.println("Hello Child");
    }
}

According to the inheritance, we look at the following several examples of code, analyze what is polymorphic

Parent obj = new  Child();
obj.sayHello();

This example constitutes a polymorphism, which satisfies the three conditions polymorphism: Parenttype objreferences to the newChild subclass out, and call a method common to both.

Parent obj = new  Child();
obj.sayHello("Tom");

This example does not constitute a multi-state, although it is to satisfy the reference point to a derived class of the base class, but it calls the specific method of the parent class.

Parent obj = new  Parent();
obj.sayHello();

This example does not meet the multi-state, it uses a reference point to the parent class's parent class, this is a normal class method calls, method calls its parent class

Child obj = new Child();
obj.sayHello();

This example does not meet the multi-state, it uses a subclass reference points to subclass, this is a normal class method calls, method calls a subclass of it

So polymorphic what good is it? Polymorphism is essentially introduced in order to avoid duplication of code, and the program more scalable, let us explain this by println function.

public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

//Class String
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Println function implements an incoming Object overloads the function call a static method of the String class valueOf, the String class with further found that this method simply calls the class toStringmethod, passing the obj can be any class that inherits Object (in Java as long as the object it must be inherited from Object), as long as the class overrides the toStringmethod can be printed directly. Such a function is realized reuse, extra heavy duty person needs println function compared to the later, it should be a lot easier.

Class type conversion

Above println function, it needs to pass a reference to the Object class, but when the method is called, has never been the type of transformation, are direct pass, here is the need for the type of transformation, in turn by a subclass to the parent class when, Java was implicit type conversion. Big turn a small must be safe (small big turn here is the relationship between memory objects contained), sub-class will be able to contain members of the parent class, so even if there is no problem converting the parent class. The parent class reference point to memory not necessarily contain a subclass members, so little to turn up unsafe.

Why should small turn big? While polymorphic gave us great convenience, but the biggest problem is polymorphic reference to the parent class subclass members can not see, that is not to use members of the subclass. This time if you want to use members of the subclass must be small to turn up operation. He said before a small turn big insecurity, due to the parent may have multiple implementation classes, we can not determine the parameter that is passed in the object subclass we need, so the introduction of a java keyword instanceofto determine whether security can be transformed , as long as the object reference is passed in the object or parent object class that the target returns true, as in the following examples

Object obj = "hello"
System.out.println(obj instanceof String); //true
System.out.println(obj instanceof Object); //true
System.out.println(obj instanceof StringBuffer); //false
System.out.println(obj instanceof CharSequence); //true

Abstract methods and classes

We can say that with polymorphic code reuse later. But sometimes we have in common for several classes, a higher-level abstract base class, but found that although there are some common base class content, but there are some methods do not know how to achieve, such as the textbook example often the animal, because they do not know exactly what the animal is, so it can not determine whether the animal is herbivorous or carnivorous. The animal is generally eatdefined as an abstract method, the method has an abstract class is an abstract base class must have.

Abstract method is a method does not need to write to achieve, it just provides a function prototype. The abstract class can not create an instance, there must be a derived class to override abstract methods. Why not create an abstract class object? Call a method on an object is essentially a function corresponding to the function table to find the memory address where the code, and abstract method is a method not implemented, naturally, we can not give the address of the method, if you create an object, and I want to call this object abstract method that is not yet on the conflict. Therefore, the provisions can not instantiate an abstract class.

Define abstract method of using keywords abstract, such as

public abstract class Life{
    public abstract void happy();
}

public class Cat{
    public void happy(){
        System.out.println("猫吃鱼");
    }
}

public class Cat{
    public void happy(){
        System.out.println("狗吃肉");
    }
}

public class Altman{
    public void happy(){
        System.out.println("奥特曼打小怪兽");
    }
}

Above defines an abstract class Life represents the biological world, you have to ask what happiness is biological, no one could give you the answer, different organisms have different answers, but specific to the same organisms, may have the answer here simply gives the answer: happiness is a cat fish dog meat love Altman played little monster.

Use an abstract class to note the following points:

  • You can not create an abstract class direct object implementation class must be used to create objects
  • All the abstract methods abstract class must implement, otherwise, the implementation class must be abstract class
  • An abstract class can have its own constructor method, which is only used when the subclass constructor
  • It must be abstract class abstract class without abstract methods, but there is an abstract method

interface

Interface is a set of common standards, they meet the general criteria can, for example, a USB interface, as long as a device using a USB port, so my computer no matter what your device is plugged in it should be used. In the code is a common interface specification plurality of classes.

Java, the interface is a reference type. Interfaces and abstract classes are very similar, the same can not create objects, methods, implementation class must be created. Interfaces and abstract classes but there are some different. An abstract class is a class that is a class of higher-level abstracted from the underlying class, but the interface is generally used to link multiple classes, a common standard is needed to achieve more than one class. It is extended out from the top layers.

A common usage scenario is a callback interface, such as common window message processing function. This scenario is generally used C ++ function pointers, but the main use Java interface.
Interface keyword interfaceto define, for example,

public interface USB{
    public final String deviceType = "USB"; 
    public abstract void open();
    public abstract void close();
}

Common interface is a member of the abstract methods, abstract methods are also implemented by the implementation class, precautions also before the same abstract class. In addition to the abstract method, the interface may also have constant.

Abstract methods interface is no method body, it needs to achieve class to achieve, so to achieve the implementation class will be called upon to rewrite phenomenon occurs classes and interfaces, so constant it?

public class Mouse implements USB{
    public final String deviceType = "鼠标";
    public void open(){

    }

    public void close(){

    }
}

public class Demo{
    public static void main(String[] args){
        USB usb = new Mouse();
        System.out.println(usb.deviceType);
    }
}

Way attribute members called to say before calling reload the constant follow. Use what type of reference, the members of which type of call.

Another important difference with the abstract class is the interface to run multiple inheritance, then the question of whether the conflict will appear in multiple-inheritance interfaces in it

public interface Storage{
    public final String deviceType = "存储设备";
    public abstract void write();
    public abstract void read();
}

public class MobileHardDisk implements USB, Storage{
     public void open(){

    }

    public void close(){

    }

    public void write(){

    }

    public void read(){

    }
}

public class Demo{
    public static void main(String[] args){
        MobileHardDisk mhd = new MobileHardDisk();
        System.out.println(mhd.deviceType);
    }
}

When you compile the above code will find the error, suggesting USB 中的变量 deviceType 和 Storage 中的变量 deviceType 都匹配, that Java is still not completely avoid conflicts.

The default interface methods

Sometimes such a scenario may occur when the project is completed, the customer needs may have changed, resulting in the interface may be added in a way, if you use an abstract method, then all of the interface implementation class had to repeat implement a method, such as said above code, USB interface, you need to add a method to inform my PC equipment What type of USB devices to the operating system matches the corresponding drive. USB implementation it may need to add a class, which could introduce a large number of duplicate code, address this issue, start from Java 8 introduces a default method.

The default method to solve the problem of the interface upgrade, when the new default interface method, without modification before implementation class.

Using the default method is as follows:

public interface USB{
    public final String deviceType = "USB"; 
    public abstract void open();
    public abstract void close();
    public default String getType(){
        return this.deviceType;
    }
}

The default method can also be overwritten with all implementation class.

Interface Static method

Starting with Java 8, allows to define static methods in an interface, static methods can be used to achieve the object class of call, you can use the interface direct call name

Interface private methods

Define private methods from Java 9 runs in the interface, private ways to address the presence of a large number of duplicate code in the default method.

Although Java is the new interface and extended attribute so much, but I think as a last resort, Do not mess with these things, after all, the interface should define a set of standards to be achieved, rather than trying to achieve these standards.

To sum up some of the considerations to use interface:

  • Interface block or no static constructor
  • A parent class is only one class but can implement multiple interfaces
  • If you have the same name as the default method of the class that implements multiple interfaces, then implementation class must override this method to achieve, or will conflict.
  • If the interface implementation class does not implement all of the abstract methods, then this class must be abstract class
  • The parent class and interface methods have the same name, priority use of the parent class, inheritance in Java interfaces to achieve better relations
  • Between the interface and the interface is multiple inheritance, if the default method of the same name exists in more than one parent interfaces, sub-interfaces need to override the default method, otherwise there will be conflicts

    final keyword

    Previously mentioned final keyword, used to represent constants, that is, the amount can not be changed in the program. In addition to this usage, it also has other uses
  • Modified class that represents the class can not have subclasses. Inheritance can be understood as a change of this kind, since it represents the final constants can not be changed, then the class nature can not be modified
  • Modification methods: the modified final method can not be overridden
  • Modified member variable: The member variables are constant and can not be modified
  • Modified local variables: local variable that is constant, can not be modified in the corresponding scope


Guess you like

Origin www.cnblogs.com/lanuage/p/10959288.html