Home  >  Article  >  Java  >  Detailed explanation of abstract class instances in java

Detailed explanation of abstract class instances in java

零下一度
零下一度Original
2017-07-26 17:37:351998browse

Abstract class:

1. The class itself containing one or more abstract methods must be Declared as abstract.

2. In addition to abstract methods, abstract classes can also contain concrete data and specific methods

3. Two options for extending abstract classes (the specific implementation of abstract methods is in subclasses) :

A. If an abstract class defines some abstract classes or does not define abstract class methods, then the subclass must also be marked as an abstract class.

B. Define all abstract methods so that the subclass is not abstract

4. It cannot be instantiated directly, but can be used indirectly

5. If a class To inherit an abstract class, you must implement the abstract method declared in the abstract class

If not, you need to declare yourself as an abstract class (this may be a question)

Let’s talk about the new features of interfaces in JDK8:

Interfaces can no longer only use abstract methods, you can add specific methods, which can be static or non-static Yes, the keyword defualt must be used in front of non-static methods.

Static methods can only be referenced by sockets, and non-static methods can only be referenced by objects instantiated by the implement class. Therefore, when the static method names of two interfaces are the same, there will be no problem and they can only be referenced by the class name of the interface.. Problems will arise with non-static methods, because the object does not know which interface method to use, causing compilation failure.

Let’s demonstrate it with code

package 面向对象;//JDK8的接口新特性。interface A
    {public abstract void hehe();//传统抽象方法public static void haha()//静态方法        {
            System.out.println("haha");
        }public default void lala()
        {
            System.out.println("lala");//非静态要加关键字default        }
    }public class Test implements A
{public static void main(String[] args)//因为不是抽象的所以可以重写也可以直接使用。    {
        A.haha();//不能被Test调用new Test().lala();//非静态要创建实例使用    }
    
}

The magic is that there are abstract methods, The subclass does not override the abstract method, and the virtual machine does not report an error, indicating that the interface does not need to write the default abstract method.

The above is the detailed content of Detailed explanation of abstract class instances in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn