Three major characteristics of Java abstract classes and oop

3.major characteristics of Java abstract classes and oop

Object-oriented has three main characteristics: inheritance and polymorphism, and encapsulation.

1. abstract class

Before understanding abstract classes, let's first understand abstract methods. An abstract method is a special method: it has only a declaration, but no concrete implementation. The declaration format of the abstract method is:

abstract void fun(); 

Abstract methods must be modified with the abstract keyword. If a class contains abstract methods, it is called an abstract class, and the abstract class must be modified with the abstract keyword before the class. Because abstract classes contain methods that have no concrete implementation, abstract classes cannot be used to create objects. The declaration format of the abstract class is as follows:

public  abstract class ClassName {    abstract void fun();
} 

Here is a problem to pay attention to: In the book "Java Programming Thoughts", abstract classes are defined as "classes containing abstract methods", but later found that if a class does not contain abstract methods, it is also an abstract class if it is only decorated with abstract. In other words, abstract classes do not necessarily have to contain abstract methods. Personally, I think this is a bit of a problem, because if an abstract class does not contain any abstract methods, why should it be designed as an abstract class? So remember this concept for the time being, and don't have to go into the details.

In the object-oriented field, because abstract concepts have no corresponding specific concepts in the problem domain, abstract classes used to represent abstract concepts cannot be instantiated. At the same time, the abstract class embodies the idea of data abstraction and is a mechanism for achieving polymorphism. It defines a set of abstract methods, and the concrete manifestation of this set of abstract methods is implemented by derived classes. At the same time, the abstract class provides the concept of inheritance. Its starting point is to inherit, otherwise it has no meaning. For a parent class, if one of its methods is implemented in the parent class without any meaning and must be implemented differently according to the actual needs of the subclass, then this method can be declared as an abstract method. At this time, this class is also It becomes an abstract class.

Pay attention to the following points when using abstract classes:

1. 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, like a normal class, can also have member variables and ordinary member methods

2. If a non-abstract class inherits an abstract class, the non-abstract class must implement all the abstract methods of the abstract parent class

3. The abstract method in the subclass cannot have the same name as the abstract method in the parent class

4. Abstract classes cannot create entities, because abstract classes have abstract methods, and abstract methods have no entities. After creating objects, it makes no sense for abstract objects to call abstract methods.

5. There must be a constructor in the abstract class. Mainly to initialize the attributes in the abstract class. Usually implemented by subclasses

6. Can final and abstract modify a method at the same time, because after the final modification, the modified class means that it cannot be inherited, and the modified method cannot be overridden. The abstract modified class is used to be inherited, and the modified method is used to be overridden

Abstract cannot modify the same method as private, because private members are invisible to the outside and can only be used in this class, so that subclasses cannot override abstract methods

Abstract cannot modify the same method as static. Static modified methods can be called with the class name, and there is no specific method implementation for abstract modified methods, so they cannot be called directly

Abstract classes and interfaces

Interface is called interface in English. In software engineering, interface generally refers to methods or functions for others to call. From here, we can understand the original intention of the designers of the Java language. It is an abstraction of behavior without concrete implementation, and the interface itself is not a class. At the same time, the implementation class that implements the interface must implement all the methods of the interface. By using the implements keyword, he indicates that the class is following a specific interface or a set of specific interfaces. It also means that "interface is just its appearance, but now Need to declare how it works".

Interface is an extension of abstract class. Java can't multiple inheritance in order to ensure data security. That is to say, inheritance can only exist in one parent class, but the interface is different, a class can implement multiple interfaces at the same time, regardless of whether there is any Therefore, the interface makes up for the defect that the abstract class cannot be multiple inherited, but it is recommended to use inheritance and interface together, because this can ensure data security and achieve multiple inheritance. The interface declaration form is as follows:

public  interface InterfaceName {

} 

In the process of using the interface, you need to pay attention to the following issues:

1. The method ownership of an Interface is automatically declared as public. To be precise, it can only be public. Of course, you can display the declarations as protected and private, but compilation errors will occur!

2. All variables defined in the interface are public static final by default, that is, since static constants are constants, they must be assigned when they are defined. They can be directly accessed through the interface name: ImplementClass.name.

3. The method defined in the interface cannot have a method body. The methods defined in the interface add public abstract by default

4. Those with abstract functions are not necessarily abstract classes, but can also be interface classes.

5. Since the methods in the interface are abstract by default, the interface cannot be instantiated.

6. Class implementation The interface is implemented through implements. The non-abstract class that implements the interface must implement all the methods of the interface, and the abstract class does not need to be implemented.

7. If the implementation class wants to access the members of the interface, the super keyword cannot be used. Because there is no explicit inheritance relationship between the two, and the member properties in the interface are static

8. There is no construction method for the interface.

9. You cannot use the new operator to instantiate an interface, but you can declare an interface variable, which must refer to an object of a class that implements the interface. You can use instanceof to check whether an object implements a specific interface.

For example: if(anObject instanceof Comparable){}.

10. Be sure to avoid duplication of method names when implementing multiple interfaces.

The difference between abstract class and interface

1. The difference at the grammatical level

1) Abstract classes can provide the implementation details of member methods (that is, ordinary methods), while only public abstract methods can exist in interfaces;

2) The member variables in the abstract class can be of various types, while the member variables in the interface can only be of public static final type;

3) The interface cannot contain static code blocks and static methods, while abstract classes can have static code blocks and static methods;

4) A class can only inherit one abstract class, but a class can implement multiple interfaces. Java is single inheritance and multiple implementations.

2. The difference in design

1) An abstract class is an abstraction of a thing, that is, an abstraction of a class, and 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 part of the class (behavior).

2) The abstract class embodies an inheritance relationship, and inheritance is an "is-a" relationship, while interface implementation is an "has-a" relationship. If a class inherits an abstract class, the subclass must be the type of abstract class, and the interface implementation depends on whether or not it has the relationship. For example, the bird is designed as a class of Bird, but the characteristic of flying cannot be designed as a class. Therefore, it is only a behavioral characteristic, not an abstract description of a class of things. At this time, you can design flight as an interface Fly, including the method fly( ). For different kinds of birds, you can directly inherit the Bird class, and whether the bird can fly (or whether it has the characteristic of flying), can fly can realize this interface , Can t fly, don t implement this interface.

3) The design level is different. As the parent class of many subclasses, the abstract class is a template design. The interface is a code of conduct, it is a radial design. For abstract classes, if you need to add new methods, you can directly add concrete implementations in the abstract class, and the subclass can be left unchanged; for interfaces, it s not. If the interface is changed, all classes that implement this interface must Make the corresponding changes.

2. inheritance

Inheritance is a technology that uses the definition of an existing class as a basis to create a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but it cannot selectively inherit the parent class. By using inheritance, we can reuse the previous code very conveniently, which can greatly improve the efficiency of development.

Inherited characteristics:

1. The subclass has non-private properties and methods of the parent class

2. The subclass can have its own attributes and methods, that is, the subclass can extend the parent class

3. The subclass can implement the method of the parent class in its own way (method overriding)

4. The constructor cannot be inherited

5. Inheritance is implemented using the extends keyword

Overriding

The polymorphism between the parent class and the child class redefines the function of the parent class. If a method defined in a subclass has the same name and parameters as its parent class, we say that the method is overridden. In Java, subclasses can inherit the methods in the parent class without the need to rewrite the same methods. But sometimes the subclass does not want to inherit the method of the parent class intact, but wants to make certain modifications, which requires method rewriting. Method overriding is also called method overriding; 
if a method in the subclass has the same method name, return type, and parameter list as a method in the parent class, the new method will overwrite the original method. Then if the object of the subclass calls this function, it must call the rewritten function. If you need the original method in the parent class, you can use the super keyword, which refers to the parent class of the current class; when the 
subclass overrides the function of the parent class, the return value type must be the return value type of the parent class function or The subclass of the return value type cannot return a data type larger than the parent class;

The access modification authority of the subclass function cannot be less than that of the parent class; the 
subclass cannot override the private method of the parent class. 
The principle when the subclass object finds properties or methods: the principle of proximity.

If the object of the subclass calls the method, the default is to use this to search first. If the current object does not find the property or method, find the object pointed to by the super keyword maintained in the current object. If the compilation error is not found, it will be called directly.

Overloading

Method overloading is a means for a class to handle different types of data in a uniform way. Multiple functions with the same name exist at the same time, with different numbers/types of parameters. Overloading is a manifestation of polymorphism in a class; 
Java method overloading means that multiple methods can be created in a class. They have the same name but different parameters and different definitions. When methods are called, the number of different parameters passed to them and the number of different parameters and the number of different parameters and the number of parameter types to them are used to determine which method to use. This is polymorphism; 
overloading When the method name is the same, but the parameter type and number are different, the return value type can be the same or different, and the return type cannot be used as the distinguishing standard
for overloaded functions ;  all overloaded functions must be in the same class in

3. polymorphism

The definition of polymorphism: refers to allowing different types of objects to respond to the same message. That is, the same message can adopt a variety of different behaviors depending on the sender. (Sending a message is a function call) 
The technology to achieve polymorphism is called dynamic binding, which refers to judging the actual type of the referenced object during execution, and calling its corresponding method according to its actual type. 
The role of polymorphism: to eliminate the coupling relationship between types. 
In reality, there are too many examples of polymorphism. For example, the action of pressing the F1 key, if the current pop-up in the Flash interface is the help file of AS 3; if the current pop-up is in Word, it is Word help; in Windows, the pop-up is Windows help and support. The same event occurs on different objects will produce different results. 
3.necessary conditions for the existence of polymorphism

Disadvantages of polymorphism: Improve extensibility, but you can only use parent class references to point to parent class members.

note:

In the case of polymorphism, when there are members (member variables and member functions) with the same name in a character class, the members of the parent class are accessed, and the member functions of the subclass are accessed only when they are non-static member functions with the same name;

When polymorphism is used for formal parameter types, multiple types of data can be accepted;

When polymorphism is used to return a type, multiple types of data can be returned. Polymorphism is used, and the type of the variable defined must be consistent with the returned type.

The following example analyzes polymorphism

public class A {  
    public String show(D obj) {  
        return ("A and D");  
    }  

    public String show(A obj) {  
        return ("A and A");  
    }   

}  public class B extends A{  
    public String show(B obj){  
        return ("B and B");  
    }  

    public String show(A obj){  
        return ("B and A");  
    }   
}  public class C extends B{  }  public class D extends B{  }  public class Test {  
    public static void main(String[] args) {  
        A a1 = new A();  
        A a2 = new B();  
        B b = new B();  
        C c = new C();  
        D d = new D();  

        System.out.println("1--" + a1.show(b));  
        System.out.println("2--" + a1.show(c));  
        System.out.println("3--" + a1.show(d));  
        System.out.println("4--" + a2.show(b));  
        System.out.println("5--" + a2.show(c));  
        System.out.println("6--" + a2.show(d));  
        System.out.println("7--" + b.show(b));  
        System.out.println("8--" + b.show(c));  
        System.out.println("9--" + b.show(d));        
    }  
}   

The output result is:

1--A and A  2--A and A  3--A and D  4--B and A  5--B and A  6--A and D  7--B and B  8--B and B  9--A and D   

1. let s look at a sentence: When a superclass object references a subclass object, the type of the referenced object, not the type of the reference variable, determines whose member method is called, but the called method must be in the superclass Defined, which means that the method being called must be a method overridden by a subclass. This sentence is a generalization of polymorphism. In fact, there is a priority for calling object methods in the inheritance chain: this.show(O), super.show(O), this.show((super)O), super.show((super)O).

The meaning of the first half sentence is: when the parent class variable refers to the subclass object, when calling the member function, the member function of the subclass should be called, but the premise is that this function is a function overridden by the subclass.

The inheritance relationship of ABCD is as follows: 

Analysis:

For 1 and 2, B and C belong to the subclasses of A, call a1.show(b), a1.show(b), you can find A.show(A boj), because in the case of polymorphism, the parent class is the formal parameter At the time, the actual parameters of its subclasses can be accepted.

For 3, you can find A.show(D odj) directly.

For 4, originally because a2 refers to an object of its subclass B, the member function called should be B.show(B obj), but because B.show(B obj) is not an overridden function, it will not Call B.show(B obj). Therefore, according to the priority, first look at this.show(O), and the show(B obj) method is not found in class A, so we go to the super (super class) of A, and A has no super class, so go to the third Priority this.show((super)O), this is still a2, where O is B, (super)O is (super)B is A, so it looks for the show(A obj) method in class A, class A has this method, but because a2 refers to an object of class B, and B overrides the show(A obj) method of A, it is finally locked to show(A obj) of class B, and the output is "B and A" .

For 5, according to the priority, look at this.show(O) first, and the show(C obj) method is not found in class A, so go to the super (superclass) of A, and A has no superclass, so turn To the third priority this.show((super)O), this is still a2, where O is C, because A is the superclass of C, so it looks for the show(A obj) method in class A, class A There is this method, but because a2 refers to an object of class B, and B overrides the show(A obj) method of A, it is finally locked to show(A obj) of class B, and the output is "B and A".

For 6, also according to the priority, first look at this.show(O), and just find the show(D obj) method in class A, and the output is "D and A".

For 7, you can call this.show(O) directly.

For 8, also according to the priority, first look at this.show(O), and the show(C obj) method is not found in class B, so look for the super (superclass) of B, and show() is not found in class A. C obj) method, so go to the third priority this.show((super)O), this is still b, where O is C, because B is the superclass of C, so it goes to class B to find show(B obj) method, so the output is "B and B".

For 9, also according to the priority, first look at this.show(O), and the show(D obj) method is not found in class B, so go to the super (superclass) of B to find, and show() is found in class A D obj) method, so the output is "A and D".

4. packaging

Encapsulation refers to the use of abstract data types to encapsulate data and data-based operations to form an indivisible and independent entity. The data is protected inside the abstract data type. The internal details are hidden as much as possible, and only some external ones are retained. The interface makes it contact with the outside world. Other objects of the system can only communicate and interact with this encapsulated object through authorized operations wrapped outside the data. In other words, the user does not need to know the internal details of the object (of course, no way to know), but can access the object through the external interface provided by the object.

There are four major benefits of using encapsulation:

1. Good packaging can reduce coupling.

2. The internal structure of the class can be modified freely.

3. More precise control of members can be carried out.

4. Hide information and implement details.

Scan the QR code below to follow the WeChat official account!

Share Java dry goods daily!