当前位置:网站首页>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~
边栏推荐
- Short video platform development, click links and pictures to automatically jump to a new page
- 多线程实现 重写run(),怎么注入使用mapper文件操作数据库
- 2022年全国最新消防设施操作员(初级消防设施操作员)模拟题及答案
- 知识点滴 - 关于汉语学习的网络资源
- mysql导入文本文件时的pager
- Establishment of SSH Framework (Part 2)
- E-week finance Q1 mobile banking has 650million active users; Layout of financial subsidiaries in emerging fields
- Moonbeam integrates coin98, giving users more choices on the multi chain road
- 100+数据科学面试问题和答案总结 - 机器学习和深度学习
- 几百行代码实现一个脚本解释器
猜你喜欢

Taco: a data enhancement technique for character recognition

Necessary skills for test and development: actual combat of security test vulnerability shooting range

Congratulations to myself, official account has more than ten thousand fans

多线程实现 重写run(),怎么注入使用mapper文件操作数据库

Google Earth engine (GEE) - global flood database V1 (2000-2018)

mysql导入文本文件时的pager

Difference between curdate() and now()
![[Matlab bp regression prediction] GA Optimized BP regression prediction (including comparison before optimization) [including source code 1901]](/img/73/1e4c605991189acc674d85618cf0ef.png)
[Matlab bp regression prediction] GA Optimized BP regression prediction (including comparison before optimization) [including source code 1901]

Project practice! Teach you JMeter performance test hand in hand

机器人学DH参数及利用matlab符号运算推导
随机推荐
Light collector, Yunnan Baiyao!
JS reverse massive star map sign signature
恭喜我自己,公众号粉丝破万
2022年安全员-B证考试题库及答案
Short video platform development, click links and pictures to automatically jump to a new page
一文详解|增长那些事儿
S32ds jump to defaultisr
Are test / development programmers really young? The world is fair. We all speak by strength
flinkcdc采集oracle,oracle数据库是CDB的
创新之源 理解通透 二
Establishment of SSH Framework (Part 2)
短视频本地生活版块成为热门,如何把握新的风口机遇?
求一个能判断表中数据,只填充不覆盖的sql
现代交换原理MOOC部分题目整理
Notepad++ -- column editing mode -- Usage / instance
PHP code wechat, official account and enterprise wechat send emoticons [u+1f449]
Difference between curdate() and now()
How to clean the nozzle of Epson l3153 printer
Analyse complète annuelle du marché chinois de l'audio en 2022
[proteus simulation] timer 1 external counting interrupt