In-depth understanding of abstract classes and interfaces in Java
Nov 27, 2019 pm 04:43 PM I believe everyone has this feeling: abstract classes and interfaces have too many similarities and too many differences. These two often make beginners confused. Whether in actual programming or during interviews, abstract classes and interfaces are particularly important! I hope that after reading this article, everyone can calmly understand the two...
What I understand about abstract classes
1. Abstract classes have the same flavor as classes.
1) Abstract classes can be used the same as classes. To inherit2), abstract classes can have all the components that a class can have [including constructors, static static modification components, etc.]
Abstract class is just as the name defines it, it is also A class
2, abstract method
It is necessary to know first before talking about different charmsAbstract method:
2), abstract method must be modified with
abstract keyword
3), has abstraction The class of the method must be an abstract class
4). The abstract method must be
public or
protected. By default, it is
public
Abstract classes do not necessarily have abstract methods
3. The strange charm of abstract classes and classes
1) , Abstract classes must be modified with the abstract keyword. Classes modified with abstract are abstract classes!2), abstract classes may or may not have abstract methods
3), although abstract classes have constructors, they cannot be used to directly create object instances
4), abstract classes cannot use
final,
privateModification
5) External abstract classes cannot be modified with Static, but internal abstract classes can be declared with static. The code to understand this sentence is as follows:
//定義一個(gè)抽象類(lèi)A abstract class A{ //定義一個(gè)內(nèi)部抽象類(lèi)B static abstract class B{ //static定義的內(nèi)部類(lèi)屬于外部類(lèi) public abstract void saoMethod(); } } class C extends A.B{ public void saoMethod(){ System.out.println("======saoMethod方法執(zhí)行了======"); } } public class StaticDemo { public static void main(String[] args) { A.B ab = new C();//向上轉(zhuǎn)型 ab.saoMethod(); } } 運(yùn)行結(jié)果: ======saoMethod方法執(zhí)行了======Some children's shoes are confusing.
C extends A.BWhat kind of cool operation is it? Can you still play like this? Yes, when the internal abstract class declared using
static is equivalent to an external abstract class, the class name is expressed in the form of "external class.inner class" when inheriting. This kind of cool operation is really safe and skinny.
Abstract class is a special class. There is an essential difference between abstract class and ordinary class
4. Master abstract class
Abstract classes exist for inheritance. If you define an abstract class but do not inherit it, the abstract class created will be meaningless!Although abstract classes have constructors, they cannot be directly Being instantiated, creating an object involves upward transformation, which is mainly used to be called by its subclasses
There is also the sentence that abstract classes can have no abstract methods. This is just an important thing to remember. Concept, be sure to remember! In actual development, abstract classes generally have abstract methods, otherwise the abstract class will lose its meaning and be no different from an ordinary class! If an ordinary class A inherits an abstract class B, the subclass A must implement all the abstract methods of the parent class B. If subclass A does not implement the abstract method of parent class B, subclass A must also be defined as an abstract class, that is, an abstract class.Interface as I understand it
Interface can be said to be a special case of abstract class. Abstract class and interface are two There are too many similarities and too many differences. In contrast, an interface is more like an abstraction of behavior!1. Interface characteristics
1),methods in the interface default to public abstractType, the member variable in the interface type is not written and defaults to public static final. 2), the interface has no construction method
3), the interface can implement "multiple inheritance", a class can implement multiple interfaces, the implementation format is to directly separate them with commas.
2. Must know about interfaces
Interfaces can only containpublic static final variables. If not written, the default is
public static final, modified with
private will cause compilation failure.
public abstract methods and can only be
public abstract methods, using other keywords, such as
Modifications such as private, protected, static, final will fail to compile.
3. Interface misunderstandings
Many articles on the Internet say that all methods in the interface are abstract methods. The blogger went back and did some research and found that in fact it is not enough. Seriously, let’s just look at a simple programpackage InterfaceDemo; interface AA{ //接口AA default void hh(){ System.out.println("123"); }; } class BB implements AA{ //實(shí)現(xiàn)接口 } public class InterfaceDesign { public static void main(String[] args) { AA a=new BB(); //通過(guò)實(shí)現(xiàn)類(lèi)創(chuàng)建實(shí)例 a.hh(); } } 運(yùn)行結(jié)果: 123
顯然hh
方法并不是抽象方法,但是這樣設(shè)計(jì)就失去接口的意義了,實(shí)際開(kāi)發(fā)中不會(huì)出現(xiàn)這樣的代碼,確實(shí)有點(diǎn)專(zhuān)牛角尖的韻味,所以我也不否認(rèn)網(wǎng)上的言論,只是覺(jué)得不夠嚴(yán)謹(jǐn),我覺(jué)得大家還是注意一下比較好...如果面試官聽(tīng)到你這樣的回答,可能對(duì)你刮目相看,會(huì)認(rèn)為你是一個(gè)對(duì)知識(shí)極度向往、探索以及有個(gè)人思維想法的學(xué)習(xí)者 ~說(shuō)白了,就是杠精,這里杠精是褒義詞~
抽象類(lèi)和接口本質(zhì)區(qū)別
抽象類(lèi)和接口本質(zhì)區(qū)別主要從語(yǔ)法區(qū)別和設(shè)計(jì)思想兩方面下手
1、語(yǔ)法區(qū)別
1.抽象類(lèi)可以有構(gòu)造方法,接口中不能有構(gòu)造方法。
2.抽象類(lèi)中可以有任何類(lèi)型成員變量,接口中只能有
public static final
變量3.抽象類(lèi)中可以包含非抽象的普通方法,接口中的可以有非抽象方法,比如
deaflut
方法4.抽象類(lèi)中的抽象方法的訪問(wèn)類(lèi)型可以是
public
,protected
和(默認(rèn)類(lèi)型,雖然eclipse
下不報(bào)錯(cuò),但應(yīng)該也不行),但接口中的抽象方法只能是public
類(lèi)型的,并且默認(rèn)即為public abstract
類(lèi)型。5.抽象類(lèi)中可以包含靜態(tài)方法,接口中不能包含靜態(tài)方法
6.抽象類(lèi)和接口中都可以包含靜態(tài)成員變量,抽象類(lèi)中的靜態(tài)成員變量的訪問(wèn)類(lèi)型可以任意,但接口中定義的變量只能是
public static final
類(lèi)型,并且默認(rèn)即為public static final
類(lèi)型。7.一個(gè)類(lèi)可以實(shí)現(xiàn)多個(gè)接口,但只能繼承一個(gè)抽象類(lèi)。
2、設(shè)計(jì)思想?yún)^(qū)別
對(duì)于抽象類(lèi),如果需要添加新的方法,可以直接在抽象類(lèi)中添加具體的實(shí)現(xiàn)(相當(dāng)于寫(xiě)普通類(lèi)的普通方法并添加方法體的實(shí)現(xiàn)代碼),子類(lèi)可以不進(jìn)行變更;而對(duì)于接口則不行,如果接口進(jìn)行了變更,則所有實(shí)現(xiàn)這個(gè)接口的類(lèi)都必須進(jìn)行相應(yīng)的改動(dòng)。這一點(diǎn)應(yīng)該很好理解。
從設(shè)計(jì)角度來(lái)講抽象類(lèi)是對(duì)一種對(duì)類(lèi)抽象,抽象類(lèi)是對(duì)整個(gè)類(lèi)整體進(jìn)行抽象,包括屬性、行為。而接口是對(duì)行為的抽象,接口是對(duì)類(lèi)局部(行為)進(jìn)行抽象。從某一角度來(lái)講,接口更像是抽象的抽象!
怎么理解上面這段話呢?
理解二者設(shè)計(jì)思想的區(qū)別從程序員宜春和花姑娘(一頭可愛(ài)的小母豬)的故事開(kāi)始,程序員宜春每天過(guò)著三點(diǎn)一線的生活,不是吃就是睡覺(jué),閑暇之余還會(huì)敲敲代碼,而花姑娘就厲害了,每天都是一點(diǎn)一線的生活,不是吃就是睡覺(jué),閑暇之余不是吃就是睡覺(jué)。程序員宜春和花姑娘都過(guò)著幸福安逸的生活,突然有一天,風(fēng)起云涌,天射大便~天色大變~,萬(wàn)惡的產(chǎn)品經(jīng)理來(lái)需求了,要設(shè)計(jì)一個(gè)程序員宜春和花姑娘的一個(gè)程序,要求使用抽象類(lèi)或者接口去設(shè)計(jì),這個(gè)時(shí)候你會(huì)怎么去設(shè)計(jì),下面給出兩個(gè)設(shè)計(jì)方案...
方案一:使用抽象類(lèi)設(shè)計(jì),分別設(shè)計(jì)eat、sleep、qiaoDaiMa
方法,具體代碼如下:
abstract class Myclass{ public abstract void eat(); public abstract void sleep(); public abstract void qiaoDaiMa(); }
方案二:使用接口設(shè)計(jì),分別設(shè)計(jì)eat、sleep、qiaoDaiMa
方法,具體代碼如下:
interface Myclass{ public abstract void eat(); public abstract void sleep(); public abstract void qiaoDaiMa(); }
顯然,不管是哪個(gè)類(lèi)繼承抽象類(lèi)或者實(shí)現(xiàn)上面的接口,都會(huì)出現(xiàn)同樣的狀況:重寫(xiě)它們的抽象方法。
如果有一百個(gè)程序員宜春,上面的設(shè)計(jì)都是很好地得到解決。但是到花姑娘身上就不管用了,花姑娘不會(huì)敲代碼這種高端操作啊!一百個(gè)花姑娘都重寫(xiě)的qiaoDaiMa
方法都沒(méi)有意義啊,顯然這樣設(shè)計(jì)有問(wèn)題。
從上面可以看出,eat、sleep
對(duì)于qiaoDaiMa
方法不是同一范疇內(nèi)的行為(方法)。實(shí)際上我們可以這樣設(shè)計(jì):定義一個(gè)抽象類(lèi),包含eat、sleep
方法,再定義一個(gè)接口包含qiaoDaiMa
方法,具體代碼如下:
abstract class Myclass{ public abstract void eat(); public abstract void sleep(); } interface MyclassTwo{ public abstract void qiaoDaiMa(); } class YiChun extends Myclass implements MyclassTwo{ @Override public void eat() { } @Override public void sleep() { } @Override public void qiaoDaiMa() { } }
我們只要讓一百個(gè)程序員宜春繼承抽象類(lèi)并實(shí)現(xiàn)接口就好了,而花姑娘就直接繼承抽象類(lèi)就好了。這樣一設(shè)計(jì),堪稱完美...
同樣的,這樣講述是很不負(fù)責(zé)的,為啥捏?因?yàn)槟銜?huì)發(fā)現(xiàn),這樣設(shè)計(jì)不管是抽象類(lèi)還是接口好像沒(méi)有什么區(qū)別,剛才的抽象類(lèi)換成接口,接口換成抽象類(lèi),實(shí)現(xiàn)效果也一致,代碼如下:
interface Myclass{ public abstract void eat(); public abstract void sleep(); } abstract class MyclassTwo{ public abstract void qiaoDaiMa(); }
所以,為了講解清晰設(shè)計(jì)思想?yún)^(qū)別,程序員宜春和花姑娘的故事不得不繼續(xù)講下去...
我們都知道,可愛(ài)的小母豬一般都是粉色的對(duì)吧,這個(gè)時(shí)候我們的產(chǎn)品經(jīng)理又改需求了。啥?產(chǎn)品經(jīng)理家中一百只小豬有一只是黑白sai的,額...
萬(wàn)惡的產(chǎn)品經(jīng)理只會(huì)無(wú)理改需求,可是產(chǎn)品經(jīng)理永遠(yuǎn)不會(huì)知道他一味逼程序員,程序員自己都不知道自己有多優(yōu)秀!
我們都知道,可愛(ài)的小母豬一般都是粉色的對(duì)吧,這個(gè)時(shí)候我們的產(chǎn)品經(jīng)理又改需求了。啥?產(chǎn)品經(jīng)理家中一百只小豬有一只是黑白sai的,額...
萬(wàn)惡的產(chǎn)品經(jīng)理只會(huì)無(wú)理改需求,可是產(chǎn)品經(jīng)理永遠(yuǎn)不會(huì)知道他一味逼程序員,程序員自己都不知道自己有多優(yōu)秀!
那么這個(gè)時(shí)候,我們都知道,抽象類(lèi)和接口都是可以有成員變量的,只不過(guò)接口比較苛刻只能是public static final
正是因?yàn)檫@一點(diǎn)!抽象類(lèi)和接口的設(shè)計(jì)精髓就在這里了,這個(gè)時(shí)候我們這樣設(shè)計(jì):
interface Myclass{ public abstract void eat(); public abstract void sleep(); } abstract class MyclassTwo{ String color="red"; public abstract void qiaoDaiMa(); }
讓宜春類(lèi)這樣設(shè)計(jì)
package AbstractTest; interface Myclass { public abstract void eat(); public abstract void sleep(); } abstract class MyclassTwo { String color = "red"; public abstract void qiaoDaiMa(); } class YiChun extends MyclassTwo implements Myclass { @Override public void eat() { } @Override public void sleep() { } @Override public void qiaoDaiMa() { } } public class AbstractDemo { public static void main(String[] args) { YiChun yc = new YiChun(); } }
然而宜春對(duì)于color
這個(gè)屬性可以是不理睬的,可以當(dāng)做不存在,除非宜春不嫌棄自己也是一只紅sai佩奇哈哈哈....
而花姑娘類(lèi)就要注意了!然后讓產(chǎn)品經(jīng)理家中的100只小豬設(shè)計(jì)代碼如下;
package AbstractTest; interface Myclass { public abstract void qiaoDaiMa(); } abstract class MyclassTwo { String color = "red"; public abstract void eat(); public abstract void sleep(); } class Pig extends MyclassTwo { @Override public void eat() { } @Override public void sleep() { } } public class AbstractDemo { public static void main(String[] args) { Pig p = new Pig (); String color = "blackWhite"; System.out.println(color); } }
其余的99只花姑娘就直接不用動(dòng)了也就是不需要String color = "blackWhite"
;這一句代碼,它的color
屬性默認(rèn)是red
了...
這個(gè)時(shí)候抽象類(lèi)和接口就不能更換了,從而抽象類(lèi)和接口的設(shè)計(jì)思想就很清晰了,你何識(shí)著咩啊~
本文來(lái)自?java入門(mén)?欄目,歡迎學(xué)習(xí)!
The above is the detailed content of In-depth understanding of abstract classes and interfaces in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
