Home >Java >javaTutorial >What is the interface? What is an abstract class?
What is an interface and what is an abstract class? With abstract classes, why do we need interfaces?
Abstract class is relative to ordinary class. Ordinary class is a complete functional class that can directly generate instantiated objects, and Ordinary classes can contain constructors, ordinary methods, static methods, constants, variables, etc. Abstract classes refer to adding abstract method components to the structure of ordinary classes, or directly declaring the class as an abstract type;
Similarly, abstract methods are relative to ordinary methods. , there will be a "{}" above all ordinary methods, which represents the method body. Methods with method bodies must be directly used by objects. Abstract methods refer to methods without a method body, and abstract methods must also be modified with the keyword abstract. A class with abstract methods is an abstract class, and abstract classes must be declared using the abstract keyword.
The following is a simple abstract class:
package abstractdemo; //抽象类 public abstract class AbstractDemo { //抽象方法,没有方法体 public abstract void test(); public void test1(){ System.out.println("普通方法"); } public static void main(String[] args) { Class18f2cef21ebec83e6009fc1ed61f2bdf c = AbstractDemo.class; System.out.println(c.getName()); } }
Instance of abstract class:
package abstractdemo; public abstract class AbstractTest { public static void main(String[] args) { AbstractDemo ad = new AbstractDemo() { @Override public void test() { System.out.println("实例抽象类要重写抽象类中所有的抽象方法!"); } }; ad.test(); System.out.println(ad.getClass()); } }
It can be seen from the above that abstract classes cannot be instantiated directly. Why can't it be instantiated directly? When a class is instantiated, it means that the object can call attributes or methods in the class, but there are abstract methods in abstract classes, and abstract methods have no method body, and they cannot be called without a method body. Since method calls cannot be made, how to generate instantiated objects? Therefore, when instantiating an abstract class, you will be asked to override the abstract method in the abstract class first; if there is no abstract method in an abstract class, then the class cannot be instantiated, and a compilation error will be reported during instantiation;
The principles for using abstract classes are as follows:
(1) Abstract methods must be public or protected (because if they are private, they cannot be inherited by subclasses, and subclasses cannot implement them. This method), which is public by default;
(2) Abstract classes cannot be instantiated directly and need to be handled by subclasses through upward transformation;
(3) Abstract classes must have subclasses. Use extends inheritance. A subclass can only inherit one abstract class;
(4) Subclasses (if not abstract classes) must override abstraction. All abstract methods in the class (if the subclass does not implement the abstract method of the parent class, then the subclass is also an abstract class)
Look at a piece of code below:
package abstractdemo; //抽象类 public abstract class AbstractDemo { //抽象方法,没有方法体 public abstract void test(); public void test1(){ System.out.println("普通方法"); } public static void main(String[] args) { Class18f2cef21ebec83e6009fc1ed61f2bdf c = AbstractDemo.class; System.out.println(c.getName()); } } package abstractdemo; public class Test extends AbstractDemo{ @Override public void test() { System.out.println("继承抽象类,一定要重写抽象类中的抽象方法,如果不重写,那么该类也是抽象类!"); } } package abstractdemo; public class Demo { public static void main(String[] args) { AbstractDemo ad = new Test(); ad.test(); } }
现在就可以清楚的发现:
(1)抽象类继承子类里面有明确的方法覆写要求,而普通类可以有选择性的来决定是否需要覆写;
(2)抽象类实际上就比普通类多了一些抽象方法而已,其他组成部分和普通类完全一样;
(3)普通类对象可以直接实例化,但抽象类的对象必须经过向上转型之后才可以得到。
虽然一个类的子类可以去继承任意的一个普通类,可是从开发的实际要求来讲,普通类尽量不要去继承另外一个普通类,而是去继承抽象类。
抽象类的使用限制:
1.由于抽象类里会存在一些属性,那么抽象类中一定存在构造方法,其存在目的是为了属性的初始化。抽象类中是有构造函数的,所以子类继承抽象类,构造方法的调用顺序仍然是先父类构造函数,然后子类构造函数
2.抽象类不可以修饰为final,因为抽象类有子类,而final修饰的类不能被继承;
3.外部抽象类不能被修饰为static,外部抽象类不允许使用static声明,而内部的抽象类运行使用static声明。使用static声明的内部抽象类相当于一个外部抽象类的成员,继承的时候使用“外部类.内部类”的形式表示类名称。
package com.wz.abstractdemo;static abstract class A{//定义一个抽象类public abstract void print(); }class B extends A{public void print(){ System.out.println("**********"); } }public class TestDemo {public static void main(String[] args) { A a = new B();//向上转型 a.print(); } }
执行结果
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Illegal modifier for the class A; only public, abstract & final are permitted at com.wz.abstractdemo.A.<init>(TestDemo.java:3) at com.wz.abstractdemo.B.<init>(TestDemo.java:9) at com.wz.abstractdemo.TestDemo.main(TestDemo.java:18)
再看一个关于内部抽象类:
package com.wz.abstractdemo;abstract class A{//定义一个抽象类static abstract class B{//static定义的内部类属于外部类public abstract void print(); } }class C extends A.B{public void print(){ System.out.println("**********"); } }public class TestDemo {public static void main(String[] args) { A.B ab = new C();//向上转型 ab.print(); } }
执行结果:
**********
4.任何时候,如果要执行类中的static方法的时候,都可以在没有对象的情况下直接调用,对于抽象类也一样。但是修饰为abstract的抽象方法,不能修饰为static,没有意义;
5.有时候由于抽象类中只需要一个特定的系统子类操作,所以可以忽略掉外部子类。这样的设计在系统类库中会比较常见,目的是对用户隐藏不需要知道的子类。
范例如下:
package com.wz.abstractdemo;abstract class A{//定义一个抽象类public abstract void print();private static class B extends A{//内部抽象类子类public void print(){//覆写抽象类的方法System.out.println("Hello World !"); } }//这个方法不受实例化对象的控制public static A getInstance(){return new B(); } }public class TestDemo {public static void main(String[] args) {//此时取得抽象类对象的时候完全不需要知道B类这个子类的存在A a = A.getInstance(); a.print(); } }
运行结果:
Hello World !
抽象类的应用——模板设计模式
例如,现在有三类事物:
(1)机器人:充电,工作;
(2)人:吃饭,工作,睡觉;
(3)猪:进食,睡觉。
现要求实现一个程序,可以实现三种不同事物的行为。
先定义一个抽象行为类:
package com.wz.abstractdemo;public abstract class Action{public static final int EAT = 1 ;public static final int SLEEP = 3 ;public static final int WORK = 5 ;public abstract void eat();public abstract void sleep();public abstract void work();public void commond(int flags){ switch(flags){case EAT:this.eat();break;case SLEEP:this.sleep();break;case WORK:this.work();break;case EAT + SLEEP:this.eat();this.sleep();break;case SLEEP + WORK:this.sleep();this.work();break;default:break; } } }
定义一个机器人的类:
package com.wz.abstractdemo;public class Robot extends Action{ @Overridepublic void eat() { System.out.println("机器人充电"); } @Overridepublic void sleep() { } @Overridepublic void work() { System.out.println("机器人工作"); } }
定义一个人的类:
package com.wz.abstractdemo;public class Human extends Action{ @Overridepublic void eat() { System.out.println("人吃饭"); } @Overridepublic void sleep() { System.out.println("人睡觉"); } @Overridepublic void work() { System.out.println("人工作"); } }
定义一个猪的类:
package com.wz.abstractdemo;public class Pig extends Action{ @Overridepublic void eat() { System.out.println("猪进食"); } @Overridepublic void sleep() { System.out.println("猪睡觉"); } @Overridepublic void work() { } }
测试主类:
package com.wz.abstractdemo;public class AbstractDemo {public static void main(String[] args) { fun(new Robot()); fun(new Human()); fun(new Pig()); }public static void fun(Action act){ act.commond(Action.EAT); act.commond(Action.SLEEP); act.commond(Action.WORK); } }
运行结果:
机器人充电 机器人工作 人吃饭 人睡觉 人工作 猪进食 猪睡觉
If all subclasses want to complete the operation normally, they must override according to the specified method. At this time, the function of the abstract class is the function of a class definition template.
---------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- --------------------------------------------------
An interface is a "class" that is more abstract than an abstract class. I put "class" in quotes here because I can't find a better word to express it, but we need to be clear that the interface itself is not a class, which can be seen from the fact that we cannot instantiate an interface. For example, new Runnable(); is definitely wrong, we can only new its implementation class.
The interface is used to establish a protocol between classes. What it provides is only a form without a specific implementation. At the same time, the implementation class that implements the interface must implement all methods of the interface. By using the implements keyword, it indicates that the class is following a specific interface or group of specific interfaces. It also indicates that "interface is just its appearance, but now Need to state how it works”.
Interface is an extension of abstract class. In order to ensure data security, Java cannot have multiple inheritance. That is to say, inheritance can only exist in one parent class, but the interface is different, and one class can be implemented at the same time. Multiple interfaces, regardless of whether there is a relationship between these interfaces, so interfaces make up for the defect that abstract classes cannot have multiple inheritance, but it is recommended to use inheritance and interfaces together, because this can not only ensure data security but also achieve multiple inheritance.
When using the interface, you need to pay attention to the following issues:
1. All method access rights of an Interface are automatically declared as public. To be precise, it can only be public. Of course, you can explicitly declare it as protected or private, but compilation will cause errors!
2. You can define "member variables" in the interface, or immutable constants, because the "member variables" in the interface will automatically become public static final. It can be accessed directly through the class name: ImplementClass.name.
3. There is no implemented method in the interface.
4. A non-abstract class that implements an interface must implement all methods of the interface. Abstract classes do not need to be implemented.
5. 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){}.
6. When implementing multiple interfaces, you must avoid duplication of method names.
## In the Java language, abstract class and interface are supported Two mechanisms for abstract class definition. It is precisely because of the existence of these two mechanisms that Java is given powerful object-oriented capabilities. There are great similarities between abstract class and interface in terms of support for abstract class definition, and they can even be replaced with each other. Therefore, many developers seem to be more casual about the choice of abstract class and interface when defining abstract classes. In fact, there is a big difference between the two, and their choice even reflects whether the understanding of the nature of the problem field and the understanding of the design intention are correct and reasonable.
##Abstract class
|
Interface
|
|
Class |
An inheritance relationship, a class can only use the inheritance relationship once . Multiple inheritance can be achieved by inheriting multiple interfaces |
A class can implement multiple interfaces |
Data members |
can have their own |
Static cannot be modified, that is, it must be static final. Generally, it is not defined here |
method |
Can be private, non-abstract method, abstract method must be implemented |
##It cannot be private, the default is public, abstract type |
Variables |
can be private, default is friendly Type, its value can be redefined in a subclass or reassigned |
cannot be private, the default is public static final type, and must be given to it The initial value cannot be redefined in the implementation class and its value cannot be changed. |
Design Concept |
means "is- a" relationship |
represents the "like-a" relationship |
##Implementation
|
needs inheritance and uses extends
|
requires implementations
|
批注:
|
1. Abstract classes represent an inheritance relationship in the Java language. A subclass can only have one parent class, but can have multiple interfaces.
2. An abstract class can have its own member variables and non-abstract class methods, but only static and immutable member data can exist in the interface (but generally not in the interface) defines member data), and all its methods are abstract.
3. The design concepts reflected by abstract classes and interfaces are different. Abstract classes represent the "is-a" relationship, while interfaces represent the "like- a" relationship.
Abstract classes and interfaces are two different abstract concepts in the Java language. Their existence provides very good support for polymorphism, although there are great similarities between them. . But their choice often reflects your understanding of the problem domain. Only by having a good understanding of the nature of the problem domain can we make a correct and reasonable design.
The above is the detailed content of What is the interface? What is an abstract class?. For more information, please follow other related articles on the PHP Chinese website!