Java abstract class and OOP three major features

Source: Internet
Author: User

There are three main features of Object-oriented: inheritance and polymorphism, encapsulation .

first, Abstract class

Before you learn about abstract classes, take a look at the abstract methods. An abstract method is a special method: it is only declared, and there is no specific implementation . The declarative format for an abstract method is:

Abstract void Fun ();

  abstract methods must be decorated with the abstract keyword . If a class contains abstract methods, it is called an abstract class, and the abstract class must be decorated with the abstract keyword before the class. Because abstract classes contain methods that are not specifically implemented, you cannot create objects with abstract Classes. the declaration format for an abstract class is as Follows:

public  abstract class ClassName {
    abstract void fun();


Here's a question: in the Java programming idea, the abstract class is defined as "the class containing the abstract method", but later it is discovered that if a class does not contain an abstract method, it is also an abstract class if it is simply decorated with an abstraction. That is, abstract classes do not necessarily have to contain abstract methods. Personally think this belongs to the problem of the dead, because if an abstract class does not contain any abstract method, why design as abstract class? So remember this concept for a while, without having to delve into why.

Abstract classes used to characterize abstract concepts cannot be instantiated in the object-oriented domain because abstract concepts have no corresponding specific concepts in the problem domain. At the same time, abstract class embodies the idea of data abstraction and is a mechanism to realize polymorphism. It defines a set of abstract methods that are implemented by derived classes as a concrete representation of this set of abstract methods. At the same time, abstract classes provide the concept of inheritance, The starting point is to inherit, otherwise it does not exist any meaning . For a parent class, if one of its methods is implemented in the parent class without any meaning, it must be implemented differently according to the actual needs of the subclass, then the method can be declared as an abstract method, and this class becomes the abstract class.

There are a few things to consider when using abstract classes:

1. A class containing abstract methods is called an abstract class, but it does not mean that there can be only abstract methods in an abstract class, which, like normal classes, 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 abstract methods of the abstract parent class

3. Abstract methods in subclasses cannot have the same name as the abstract methods of the parent class

4. Abstract classes cannot create entities, because abstract classes have abstract methods, and abstract methods do not have entities, and abstract objects invoke abstract methods without meaning after they are created.

5, the abstract class must have a constructor Function. Primarily in order to initialize attributes in an abstract class. Usually implemented by subclasses

6, final and abstract Whether a method can be modified at the same time, because after the final decoration, the decorated class represents can not inherit , the adornment method non-overridable,Abstract Modified class is used to be inherited, the modification method is used to be rewritten

Abstract cannot modify the same method as private, because the PRIVTE members are not visible to the outside and can only be used in this class, so the class cannot override the abstract method

Abstract cannot modify the same method as static, static decorated methods can be called with the class name, and There is no specific method implementation for the method of the abstract adornment, all cannot be called directly


abstract classes and Interfaces

interface, English is called interface, in software engineering, The interface refers to the method or function for others to Call. From here, we can realize the original intention of the Java language designer, it is the abstraction of the behavior, and no concrete implementation, the interface itself is not a class. the implementation class that implements the interface must implement all the methods of the interface, by using the implements keyword, he says that the class is following a particular interface or a specific set of interfaces, and that "interface is just the way it looks, but now you need to declare how it works."

Interface is an extension of the abstract class, Java in order to ensure that data security is not multiple inheritance, that is, inheritance can only exist a parent class , but the interface is different, a class can implement multiple interfaces at the same time , regardless of the relationship between these interfaces, therefore, the interface compensates for the fact that abstract classes cannot inherit multiple inheritance, but it is recommended that inheritance and interfaces be used together, because this ensures both data security and multiple Inheritance. The interface declaration form is as Follows:

 Public Interface InterfaceName {}

There are several issues to be aware of when using the Interface:

1, a interface party all legal access rights are automatically declared Public. onlypublic, of course, You can display the declaration as protected, private, but the compilation will be wrong!

2, all variables defined in the interface are public static final , that is, if the static constant is a constant, then the definition must be assigned a value , can be accessed directly through the interface name:

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

4, abstract function is not necessarily an abstract class, can also be an interface class.

5, because the method in the interface is abstract by default, the interface cannot be Instantiated.

6, the class implements the interface through the implements realization, the realization interface Non-abstract class must implement this interface all methods , the abstract class may not be Implemented.

7. You cannot use the Super keyword if the implementation class wants to access members in the interface . Because there is no inheritance relationship between the two, and the member property of the interface is static

8, the interface does not have a method of Construction.

9 . You cannot instantiate an interface with the new operator, but you can declare an interface variable that must reference (refer to) an object of the class that implements the Interface. You can use instanceof to check whether an object implements a particular Interface.

For example: if (anobject instanceof comparable) {}.

10, in the implementation of Multi-interface must avoid the repetition of the method Name.

The difference between an abstract class and an interface

1, the grammatical level of the difference

1) Abstract classes can provide the implementation details of the member methods (i.e., common methods), while the interface can only exist the public abstract method;

2) member variables in an abstract class can be of various types, whereas member variables in an interface are only public static final types;

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 inherit only one abstract class, while a class may implement multiple interfaces,Java is single-inheritance, multi-implementation .

2, the difference in design level

1) Abstract class is an abstraction of a thing, that is, an abstraction of a class, and an interface is an abstraction of a behavior. An abstract class is an abstraction of the whole class as a whole, including properties, behaviors, but an interface that abstracts the local (behavior) of a class.

2) the abstract class embodies an inheritance relationship, and the inheritance is a "is-a" relationship, while the interface implementation is the "has-a" Relationship. If a class inherits an abstract class, the subclass must be the kind of abstract class, and the interface implementation is the one with no or no relationship. for example, A bird is designed as a class bird, but it cannot be designed as a class, so it is just a behavioral trait, not an abstract description of a class of things. At this point, the flight can be designed as an interface fly, including the method fly (), for different kinds of birds directly inherit the bird class, and whether the bird can fly (or whether it has the characteristics of flight), can fly can realize this interface, not flying will not implement this interface.

3) The design level is different, abstract class as the parent class of many subclasses, it is a kind of template design. And the interface is a kind of behavior specification, it is a kind of radiant design. for abstract classes, If you need to add a new method, you can directly add a specific implementation in the abstract class, the subclass can not be changed, but for the interface is not, if the interface is changed, all implementations of this interface must be Modified.

Ii. inheritance

Inheritance is the technique of building a new class using the definition of an existing class, and the definition of a new class can add new data or new functionality, or it can use the functionality of the parent class, but not selectively inherit the parent class. By using inheritance, we can easily reuse the previous code, which can greatly improve the efficiency of development.

Characteristics of Inheritance:

1. Subclasses have attributes and methods that are not private to the parent class

2, subclasses can have their own properties and methods, that is, subclasses can extend the parent class

3. Subclasses can implement methods of the parent class in their own way ( method overrides )

4. constructors cannot be inherited

5. inheritance using extends keyword implementation

Rewrite overriding
    1. The polymorphism between the parent and child classes, redefining the functions of the parent class . If you define a method in a subclass that has the same name and Parameters as its parent class, we say that the method is Overridden. In java, subclasses can inherit methods from the parent class without having to rewrite the same method. But sometimes subclasses do not want to inherit the parent Class's methods, but want to make some changes, which requires a method of Rewriting. Method overrides are also called method overrides;
    2. If a method in a subclass has the same method name, return type, and Parameter table as a method in the parent class, the new method overwrites the original Method. then the object of the subclass, if called, must call the function that has been Rewritten. If you need a method in the parent class, you can use the super keyword, which references the parent class of the current class;
    3. When a subclass overrides a function of the parent class, the return value type must be the return value type of the parent class or subclass of the return value type, and cannot return a larger data type than the parent class ;

    4. The access adornment permission of a subclass function cannot be less than the parent class;
    5. Subclasses cannot override private methods of parent class
  when a subclass object looks for a property or methodprinciple: the nearest Principle.

if the object of the subclass calls the method, the default is to use this to find, if the current object does not find a property or method, find the object that the Super keyword is maintained in the current object , if you have not found the compilation error, Locate the Direct Call.

Heavy Duty overloading
    1. Method overloading is a means for a class to handle different types of data in a uniform manner . Multiple functions with the same name exist at the same time, with different number/types of parameters . Overloading is a representation of polymorphism in a class;
    2. Java's method overloading is that you can create multiple methods in a class that have the same name but have different parameters and different definitions. The method is called by the number of different arguments passed to them and parameter types to their different parameters and parameter types to their different parameters and parameter types to determine which method to use, which is polymorphism;
    3. When overloading, 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 criterion of overloaded function;
    4. All overloaded functions must be in the same class

three, polymorphic
    1. polymorphic definition : means that objects of different classes are allowed to respond to the same message. That is, the same message can be used in a variety of different ways depending on the sending Object. (sending a message is a function call)
    2. the technique of implementing polymorphism is called Dynamic binding, which is the actual type of the referenced object that is judged during execution, and its corresponding method is called according to its actual type.
    3. the role of polymorphism: to eliminate the coupling relationship between Types.
    4. in reality, There are numerous examples of Polymorphism. For example, If you press the F1 button, if the current pop-up in the Flash interface is the AS 3 help document, if Word help is currently popping up under word, Windows Help and support appears under Windows. The same event occurs on different objects and produces different results.

Three necessary conditions for polymorphic existence

      1. To have an inheritance or implementation, that is, the parent class reference variable points to the subclass of the object or the parent class reference to accept its own subclass object ;
      2. To have a rewrite;
      3. The parent class reference points to the subclass Object.

  polymorphic drawbacks : increased extensibility, but only parent class references can be used to point to parent class Members.


  In Polymorphic situations, when a character class has a member (member variable and member Function) of the same name, access is a member of the parent class, and only a non-static member function with the same name accesses the member function of the subclass;

Multiple types of data can be accepted when polymorphic is used for formal parameter types;

When polymorphic is used to return a type, multiple types of data can be returned, using a polymorphic method that defines the type of the variable to be the same as the type Returned.

Use the following example to analyze polymorphic

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--" +;  
        System.out.println("2--" +;  
        System.out.println("3--" +;  
        System.out.println("4--" +;  
        System.out.println("5--" +;  
        System.out.println("6--" +;  
        System.out.println("7--" +;  
        System.out.println("8--" +;  
        System.out.println("9--" +;        

The output 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  

first, let's take a look: when a superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass , This means that the method being called must be a method overridden by the quilt class . This statement is a generalization of polymorphism. In fact, the invocation of an object method in the inheritance chain has a (o), (o), ((super) o), ((super) o).

The first half of the sentence means that when a parent class variable refers to a subclass object, when the member function is called, the member function to the child class should be called, but only if the function is overridden by the quilt class.

The inheritance relationship of a B C D is as Follows:


For the subclass 1 and 2,b and C that belong to a, call (b), (b), You can find (A boj), because in polymorphic cases, when the parent does the formal parameter, it can accept the arguments of its child class.

For 3, (D odj) can be found directly.

For 4, the member function called should be (b Obj) because A2 refers to an object of its subclass b, but (b Obj) is not called because (b Obj) is not an overridden Function. therefore, according to the priority, (O), and Class A did not find the show (B Obj) method, so to a super (superclass), and a no superclass, so go to the third priority ((super) O), This is still a2, Here o is b, (super) o i.e. (super) b is a, so it is in class A to find the method of show (a obj), 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 , So the final lock is to show (A Obj) of class b, and the output is "b and A".

For 5, the same priority will be given to (O), and the show (C Obj) method is not found in class a, so a super (superclass) is found, and a has no superclass, so go to the third priority ((super) O), This is still a2, where O is c, because A is a superclass of c, so it is in class A to find a method of show (a obj), 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 , So the final lock is to show (A Obj) of class b, and the output is "b and A".

For 6, the same priority will be given to (O), and class A has just found the show (d Obj) method, with the output "d and A".

For 7, you can call (O) directly.

For 8, the same priority will be given to (O), and the show (c Obj) method is not found in class b, so the Super (superclass) of B is found, and Class A does not find the show (c Obj) method, so go to the third priority ( Super) o), This is still B, here O is c, because B is a superclass of c, so it is in class B to find the method of show (b obj), so the output is "b and b".

For 9, the same priority will be given to (O), and the show (d Obj) method is not found in class b, so the Super (superclass) of B is found, and class A finds the show (d Obj) method, so the output is "a and d".

four, Package

Encapsulation refers to the use of abstract data types to encapsulate data and data-based operations together to form an indivisible independent entity, the data is protected within the abstract data type, as much as possible to hide the internal details, only to retain some external interface to make it contact with the Outside. Other objects of the system can communicate and interact with this encapsulated object only through authorized operations that are wrapped outside the Data. This means that the user does not need to know the details inside the object (and of course it is unknown), but can access the object through the interface provided by the object externally.

There are four advantages to using encapsulation:

1, Good package can reduce the Coupling.

2, the structure within the class can be freely modified.

3, the member can be more precise control.

4, Hide information, Realize the Details.

Java abstract class and OOP three major features

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.