当前位置:网站首页>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~
边栏推荐
- filinCdc 的sql,多表的时候总报这个错,请问下该怎么解决呀
- 整理网上蛋糕商城项目
- Notepad++ -- common plug-ins
- 109. 简易聊天室12:实现客户端一对一聊天
- Light collector, Yunnan Baiyao!
- The second round of free public classes of the red team is coming ~ 8:00 tomorrow night!
- 学习太极创客 — MQTT 第二章(五)心跳机制
- 判断对象中是否存在某一个属性
- Is the securities account opened by qiniu safe? How to open an account
- native关键字的作用
猜你喜欢

2022年低压电工考题及答案
![[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]

TACo:一种关于文字识别的数据增强技术

Code understanding: implementing volume models for hangwriten text recognition

The growth summer challenge is coming | learn and create two major tracks, and start the tutor registration!

Pager when importing text files from MySQL

UI自动化测试框架搭建 —— 编写一个APP自动化

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

Role of native keyword

wordpress zibll子比主题6.4.1开心版 免授权
随机推荐
!‘cat‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
C语言全局变量(c文件和h文件中的全局变量、静态全局变量)使用注意事项
10: 00 interview, came out at 10:02, the question is really too
【Proteus仿真】定时器1外部计数中断
互联网的发展促进了无界零售、数字零售、即时零售等一系列新模式的出现
How to clean the nozzle of Epson l3153 printer
Recommended by Alibaba P8, Fiddler packet capturing tool (I)
Unity out ref params
Matlab exercises -- routine operation of matrix
[matlab traffic light identification] traffic light identification [including GUI source code 1908]
Audio and video technology development weekly
The coming wave of Web3
Are test / development programmers really young? The world is fair. We all speak by strength
Matlab exercises -- exercises related to symbolic operation
MySQL gets the current date of the year
现代交换原理MOOC部分题目整理
Mask's miserable and inspirational childhood, who is introverted by campus violence
2022高处安装、维护、拆除考试题及答案
Establishment of SSH Framework (Part 2)
Severe tire damage: the first rock band in the world to broadcast live on the Internet