当前位置:网站首页>Interview: what are the similarities and differences between abstract classes and interfaces?
Interview: what are the similarities and differences between abstract classes and interfaces?
2022-06-28 04:54:00 【Qinhuai grocery store】
- stay java in , Usually beginners don't understand interfaces and abstract classes , This is also an easy question to ask in an interview . Let me talk about my understanding . If there is something wrong , I hope you can correct me , Thank you for .
- 1. How to define and inherit abstract classes ?
- 2. How to define and implement interfaces ?
- 3. Summary and contrast
1. How to define and inherit abstract classes ?
We define an abstract class person.class Represents a class ( people ):
// Use keywords abstract
public abstract class person {
// An abstract way to eat , It has been realized
public void eat(){
System.out.println(" I eat in an abstract way ");
}
//public Decorated empty implementation method
public void run(){}
// No embellishment , Empty implementation
void walk(){}
//protected The method of decoration , Empty implementation
protected void sleep(){}
//private The implementation of empty decoration
private void read(){}
}
- 1. Abstract class use abstract modification , There can be abstract methods , There can also be no abstract methods at all , It can also be an implemented method , But all the methods have to be implemented , Empty implementation (
public void walk(){}) It's also a kind of realization , It can't be written, It has to be followed by braces .public void eat() - 2. Method modifiers make
public,protected,private, Or not , There is no default to only inherit under the same package , If it isprivateWhen subclasses inherit, they cannot inherit this method , There's no way to modify it . - Now let's write a
Teacher.classInherited abstract class
Inherit under the same package :
Different packages inherit :
The correct code for the same package is as follows ( Do not override private methods ):
public class teacher extends person {
@Override
public void run(){
System.out.println(" I'm an entity class method of running ");
}
@Override
void walk(){
System.out.println(" I'm an entity class way to walk ");
}
@Override
protected void sleep(){
System.out.println(" I am a method of entity class sleeping ");
}
}
- give the result as follows ( There is no way to override the abstract class to eat , So it will call the default of the abstract class ):
- The following code is rewritten
eat()Method code , Rewriting is even if it's not used@OverrideIt also works :
public class teacher extends person {
public void eat(){
System.out.println(" I'm an entity class way to eat ");
}
@Override
public void run(){
System.out.println(" I'm an entity class method of running ");
}
@Override
void walk(){
System.out.println(" I'm an entity class way to walk ");
}
@Override
protected void sleep(){
System.out.println(" I am a method of entity class sleeping ");
}
}
- give the result as follows , The way you eat is covered up :
- Abstract class cannot be instantiated , such as :
- Subclasses can implement methods of abstract classes , It can also not be realized , It can also be achieved only in part , There's no problem running like this , If it doesn't work out , Call is the default use of an empty implementation of an abstract class , In other words, there is no output , If the abstract class has an implementation , The default method of the abstract class will be output . such as :
- Abstract classes can have specific methods and properties ( Member variables )
- There are many similarities between abstract classes and ordinary classes , For example, they can all be static members and static code blocks and so on .
2. How to define and implement interfaces ?
- An interface is an abstraction of a method or action , such as
person.classWant to be a teacher , Can realize the teacher's interface , It can be understood as increasing ability . - Interface is not allowed to define property variables that are not initialized , Can define
public static final int i=5;, as well aspublic int number =0;, But it's not allowedpublic int num;Such definition , allprivateNone of the variables are allowed to appear , Here are the pictures
Definition public int number =0; The default is final Embellished , So you can't change its value :
Here is the correct interface code :Teacher.java
public interface Teacher {
public static final int i=5;
public int number =0;
public void teach();
void study();
}
- Implementation class TeacherClass.java
public class TeacherClass implements Teacher{
@Override
public void teach() {
System.out.println(" I am a teacher , I want to teach ");
System.out.println(" Interface static int yes :"+i);
}
@Override
public void study() {
System.out.println(" I am a teacher , I also want to learn ");
System.out.println(" Interface int number yes :"+number);
}
}
- Test class Test.java
public class Test {
public static void main(String[] args){
TeacherClass teacherClass = new TeacherClass();
teacherClass.study();
teacherClass.teach();
System.out.println("-----------------------------------------------------");
Teacher teacher =teacherClass;
teacher.study();
teacher.teach();
}
}
result :
analysis : The member variables defined in the interface are final Of , Immutable , To implement an interface, you must implement all the methods in the interface , You can't just implement part of , Not used static final Embellished , The default is final, At the same time, there must be initialization value , Interface cannot create objects directly , such as Teacher teacher = new Teacher() , But you can create an implementation class of the interface first , Then assign the value to the interface object .
3. Summary and contrast
abstract class | Interface |
|---|---|
Use keywords abstract modification | Use keywords interface |
Use keywords extends Implementation inheritance , You can implement only part of the method , Part of it doesn't work , Or it can't be implemented | implements To implement the interface , To implement an interface, you must implement all the methods in it |
Methods in abstract classes can be empty implementations , It can be implemented by default , But you have to bring {} | There is no implementation body for the methods in the interface , That is to say {} |
Abstract classes can have specific methods and properties , There can also be static blocks of code , Static member variable | There can be no ordinary member variables in the interface , It has to be immutable final Member variables , And all member variables must be public |
Methods in abstract classes can be public,protect,private, however private Cannot inherit , So very few people write like that , If there is no modifier , Then only classes under the same package can inherit | The interface method can only be public Or no modifier , be-all private All the embellishments are wrong |
If there are changes , Add new methods , You can directly implement the default in the abstract class , It can also be implemented in the implementation class | New methods added to the interface must be declared in the interface , Then implement it in the implementation class |
Abstract classes cannot create objects directly | Interfaces can't create objects directly , You can assign objects that implement classes |
Abstract classes can have main Method , And we can run it directly , Abstract classes can also have constructors | Interface cannot be main Method , Interfaces cannot have constructors |
So when do we use interfaces and when do we use abstract classes ?
- java There is a drawback , Only single inheritance can be implemented , I think the interface is designed to make up for single inheritance .
- Interfaces are abstractions of essence , For example, people. , It can be designed as
person.classThis abstract class , Provide relevant methods , attribute , But interfaces only provide methods , It's like adding functions , So it's the abstraction of methods . - If you need a default implementation , Or basic functions are constantly changing , So it is recommended to use abstract classes , If you just add a way , So it's recommended to use the interface , If you want to implement multiple inheritance , The interface can only be used with abstract classes to achieve the desired function .
This article is a record of the beginning of learning , It's just a primary contrast , Further study needs you to keep Keep going~
This article is for myself only ( Ben rookie ) Learn to accumulate records , Or learning notes , If there is any infringement , Please contact the author for deletion . No one is perfect , The same is true of articles , The style of writing is immature , I can't help it , Don't spray , If there are mistakes , I would also like to point out that , Be deeply grateful ~
The road to technology is not in the moment , one's nobility lasts forever , Even slowly , Go on and on .Keep going~
边栏推荐
- Unity out ref params
- Audio and video technology development weekly
- 请问下,mysqlcdc设置多并行度的话,增量数据是不是会重复?
- flinkcdc采集oracle,oracle数据库是CDB的
- Flexible IP network test tool -- x-launch
- CUPTI error: CUPTI could not be loaded or symbol could not be found.
- [matlab traffic light identification] traffic light identification [including GUI source code 1908]
- Analysis of distributed transaction solution Seata golang
- LeetCode 88:合并两个有序数组
- Distributed transaction - Final consistency scheme based on message compensation (local message table, message queue)
猜你喜欢

Sword finger offer 53 - I. find the number I in the sorted array (improved bisection)

【Matlab红绿灯识别】红绿灯识别【含GUI源码 1908期】

How do I get the STW (pause) time of a GC (garbage collector)?

灵活的IP网络测试工具——— X-Launch

How to clean the nozzle of Epson l3153 printer

The number of small stores in Suning has dropped sharply by 428 in one year. Zhangkangyang, the son of Zhang Jindong, is the actual controller

Are test / development programmers really young? The world is fair. We all speak by strength

Meta universe standard forum established

Why are cloud vendors targeting this KPI?

学习太极创客 — MQTT 第二章(四)ESP8266 保留消息应用
随机推荐
mysql修改密码报错需要怎么做
Distributed transaction - Final consistency scheme based on message compensation (local message table, message queue)
Difference between curdate() and now()
Ppt production tips
互联网的发展促进了无界零售、数字零售、即时零售等一系列新模式的出现
Where does the storm go? Whose pot is the weather forecast wrong?
The SQL of filincdc always reports this error when there are multiple tables. How can I solve it
flinkcdc采集oracle,oracle数据库是CDB的
Flexible IP network test tool -- x-launch
Aspnetcoreratelimit rate limit interface access limit current limit control
求一个能判断表中数据,只填充不覆盖的sql
How do I get the STW (pause) time of a GC (garbage collector)?
【Matlab红绿灯识别】红绿灯识别【含GUI源码 1908期】
多线程实现 重写run(),怎么注入使用mapper文件操作数据库
Audio and video technology development weekly
cgo+gSoap+onvif学习总结:8、arm平台交叉编译运行及常见问题总结
汇编常用指令
Why are cloud vendors targeting this KPI?
Precautions for using C language global variables (global variables in C and H files, static global variables)
Is it true that qiniu business school gives away securities accounts? Is it safe to open an account