当前位置:网站首页>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 isprivate
When subclasses inherit, they cannot inherit this method , There's no way to modify it . - Now let's write a
Teacher.class
Inherited 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@Override
It 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.class
Want 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 , allprivate
None 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.class
This 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~
边栏推荐
- The SQL of filincdc always reports this error when there are multiple tables. How can I solve it
- How can we speed up the chunksplitter when CDC extracts MySQL data in full?
- Necessary skills for test and development: actual combat of security test vulnerability shooting range
- Performance optimization and implementation of video codec
- UI automation test framework construction - write an app automation
- Audio and video technology development weekly
- Sword finger offer 49 Ugly number (three finger needling technique)
- Analysis of distributed transaction TCC
- 控制器的功能和工作原理
- 创新之源 理解通透 二
猜你喜欢
灵活的IP网络测试工具——— X-Launch
With favorable policies, more than 20 provinces and cities have launched the yuanuniverse development plan
One article explains in detail | those things about growth
UI automation test framework construction - write an app automation
[matlab traffic light identification] traffic light identification [including GUI source code 1908]
Project practice! Teach you JMeter performance test hand in hand
100+ data science interview questions and answers Summary - machine learning and deep learning
What to do when MySQL changes the password and reports an error
Matlab exercises -- routine operation of matrix
The second round of free public classes of the red team is coming ~ 8:00 tomorrow night!
随机推荐
灵活的IP网络测试工具——— X-Launch
有人用cdc同步到mysql发生过死锁吗?
native关键字的作用
JS reverse massive star map sign signature
Performance optimization and implementation of video codec
判断对象中是否存在某一个属性
100+ data science interview questions and answers Summary - machine learning and deep learning
2022年低压电工考题及答案
[csp-j2020] excellent splitting
27 years, Microsoft IE is over!
How to clean the nozzle of Epson l3153 printer
为什么大厂不让使用undefined
请问下,mysqlcdc设置多并行度的话,增量数据是不是会重复?
[applet] solution document using font awesome Font Icon (picture and text)
Analysis of distributed transaction solution Seata golang
求一个能判断表中数据,只填充不覆盖的sql
cgo+gSoap+onvif学习总结:8、arm平台交叉编译运行及常见问题总结
June 27, 2022: give a 01 string with a length of N. now please find two intervals so that the number of 1 and the number of 0 in the two intervals are equal. The two intervals can intersect, but not c
TACo:一种关于文字识别的数据增强技术
Function and working principle of controller