java abstract class and interface summary

An abstract class
2. Interface
The difference between abstract class and interface

An abstract class

Before learning about abstract classes, let’s first understand abstract methods. An abstract method is a special kind of method: it has only a declaration, but no concrete implementation. The declaration format of an abstract method is:

abstract void fun();

Abstract methods must be decorated with the abstract keyword. If a class contains abstract methods, the class is called abstract class, and the abstract class must be modified with the abstract keyword before the class. An abstract class cannot be used to create objects because an abstract class contains methods that have no concrete implementation.

  The following problem should be paid attention to: in the book "JAVA Programming Ideas", an abstract class is defined as "a class containing abstract methods", but later it is found that if a class does not contain abstract methods and is only modified with abstract, it is also an abstract class. That is to say, an abstract class does not necessarily have to contain abstract methods. Personally, I think this is a serious problem, because if an abstract class does not contain any abstract methods, why should it be designed as an abstract class? So keep this concept in mind for now, without getting into why.

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

  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 in vain, because you cannot use it to do anything. For a parent class, if a certain method of it 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, the class is also It becomes the abstract class.

  A class that contains abstract methods is called an abstract class, but it does not mean that an abstract class can only have abstract methods. Like ordinary classes, it can also have member variables and ordinary member methods.

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 by default.

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 superclass. If the subclass does not implement the abstract method of the superclass, the subclass must also be defined as an abstract class.

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

2. Interface

 Interface, called interface in English, in software engineering, an interface generally refers to a method or function for others to call. From here, we can appreciate the original intention of the Java language designers, which is an abstraction of behavior.

In Java, an interface is defined as follows:

public interface InterfaceName {

}

  An interface can contain variables and methods. However, it should be noted that the variables in the interface will be implicitly designated as public static final variables (and can only be public static final variables, and the private modification will report a compilation error) , and the methods will be implicitly designated as public abstract methods And it can only be a public abstract method (modified with other keywords, such as private, protected, static, final, etc., a compilation error will be reported), and all methods in the interface cannot have specific implementations, that is, the methods in the interface must be are abstract methods . From here, you can vaguely see the difference between an interface and an abstract class. An interface is an extremely abstract type, which is more "abstract" than an abstract class, and generally does not define variables in an interface.

  To make a class conform to a specific set of interfaces, use the implements keyword, in the following format:

class ClassName implements Interface1,Interface2,[....]{
}

  As can be seen, a class is allowed to conform to multiple specific interfaces . If a non-abstract class conforms to an interface, it must implement all the methods in that interface. For abstract classes that follow an interface, abstract methods in the interface may not be implemented.

3. The difference between abstract class and interface

1. Differences at the grammatical level

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

  2) Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type;

  3) An 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.

2. Differences at the design level

  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 whole class, including attributes and behaviors, but an interface abstracts a part of the class (behavior).

To give a simple example, airplanes and birds are different things, but they all have one thing in common, that is, they both fly. Then when designing, you can design the aircraft as a class Airplane, and design the bird as a class Bird, but you cannot design the feature of flight as a class, so it is only 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 respectively implement the Fly interface according to their own needs. Then there are different types of aircraft, such as fighter jets, civil aircraft, etc., which can directly inherit the Airplane. The same is true for birds, and different types of birds can directly inherit the Bird class. It can be seen from this that inheritance is a "is or not" relationship, while interface implementation is a "is there or not" 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, such as whether the bird can fly (or whether it has the feature of flying), can fly You can implement this interface, but if you can't fly, you can't implement this interface.

  2) 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 behavior, it is a radial design.

> What is template design? The simplest example, everyone has used the templates 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 need to be changed. Template A is fine, no need to re-modify ppt B and ppt C. In the radial design, for example, an elevator is equipped with some kind of alarm. Once the alarms are to be updated, they must be updated. That is to say, for an abstract class, if you need to add a new method, you can directly add a concrete implementation in the abstract class, and the subclass can not change it; but not for the interface, if the interface is changed, all the implementations of this interface Classes must be modified accordingly.

  >下面看一个网上流传最广泛的例子:门和警报的例子:门都有open( )和close( )两个动作,此时我们可以定义通过抽象类和接口来定义这个抽象概念:

abstract class Door {
 public abstract void open();
 public abstract void close(); 
} 

 或者:

 interface Door {
    public abstract void open();
    public abstract void close();  
 }

但是现在如果我们需要门具有报警alarm( )的功能,那么该如何实现?下面提供两种思路:

 > 1)将这三个功能都放在抽象类里面,但是这样一来所有继承于这个抽象类的子类都具备了报警功能,但是有的门并不一定具备报警功能;

  > 2)将这三个功能都放在接口里面,需要用到报警功能的类就需要实现这个接口中的open( )和close(),也许这个类根本就不具备open( )和close( )这两个功能,比如火灾报警器。
从这里可以看出, Door的open()、close()和alarm()根本就属于两个不同范畴内的行为,open()和close()属于门本身固有的行为特性,而alarm()属于延伸的附加行为。因此最好的解决办法是单独将报警设计为一个接口,包含alarm()行为,Door设计为单独的一个抽象类,包含open和close两种行为。再设计一个报警门继承Door类和实现Alarm接口。

    void alarm(); }   abstract class Door {
     void open();
     void close(); }   class AlarmDoor extends Door implements Alarm {
     void oepn() {
      //....
     }
     void close() {
       //....
     }
     void alarm() {
       //....
     } 
     } 
四、抽象类与接口的继承与实现关系
以线程池的例子来说明接口、抽象类以及类在继承和现实时需要注意的事项

1.接口继承接口(接口不能实现接口)

Executor是线程池的顶层接口,只有一个方法

public interface Executor {
    void execute(Runnable command);
}
public interface ExecutorService extends Executor {  
      <strong> // <span style="font-family: Verdana, Arial, Helvetica, sans-serif;">ExecutorService 接口继承自接口Executor</span></strong>  
    void shutdown();  
    boolean isShutdown();  
    boolean isTerminated();  
    boolean awaitTermination(long timeout, TimeUnit unit)  
        throws InterruptedException;  
    <T> Future<T> submit(Callable<T> task);  
}

2.抽象类实现接口(抽象类不能继承接口)

<pre name="code" class="java">public abstract class AbstractExecutorService implements ExecutorService {  
   <strong> // AbstractExecutorService 实现ExecutorService接口,不需要实现ExecutorService接口的方法,因为接口可以看做一种特殊的抽象类       // 抽象类里边的普通方法必须包含方法体,即必须有{},而抽象方法不能有方法体,必须用abstract声明。</strong>  
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) { };  
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) { };  
    public Future<?> submit(Runnable task) {};  
    public <T> Future<T> submit(Runnable task, T result) { };  
    public <T> Future<T> submit(Callable<T> task) { };  
    private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks,  
                            boolean timed, long nanos)  
        throws InterruptedException, ExecutionException, TimeoutException {  
    };  
}  

3.普通类继承抽象类或实现接口
普通类继承抽象类:必须实现抽象类的所有抽象方法和该抽象类父类的所有方法

普通类实现接口:必须实现接口及其父接口的全部方法
public interface A{  
    void a();  
}  

public interface B extends A{  
    void b();  
}  

public abstract class C implements B{  
    void c(){};  
    abstract void c1();  
}  

class D extends C{  

    @Override  
    public void b() {  
        // TODO Auto-generated method stub  
    }  

    @Override  
    public void a() {  
        // TODO Auto-generated method stub  

    }  

    @Override  
    void c1() {  
        // TODO Auto-generated method stub     
    }  

}  

class E implements B{  

    @Override  
    public void a() {  
        // TODO Auto-generated method stub      
    }  

    @Override  
    public void b() {  
        // TODO Auto-generated method stub        
    }  

}  



请尊重作者劳动成果,转载请标明原文链接http://www.cnblogs.com/dolphin0520/p/3811437.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325881065&siteId=291194637