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è)抽象類A abstract class A{ //定義一個(gè)內(nèi)部抽象類B static abstract class B{ //static定義的內(nè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(); //通過實(shí)現(xiàn)類創(chuàng)建實(shí)例 a.hh(); } } 運(yùn)行結(jié)果: 123
顯然hh
方法并不是抽象方法,但是這樣設(shè)計(jì)就失去接口的意義了,實(shí)際開發(fā)中不會(huì)出現(xiàn)這樣的代碼,確實(shí)有點(diǎn)專牛角尖的韻味,所以我也不否認(rèn)網(wǎng)上的言論,只是覺得不夠嚴(yán)謹(jǐn),我覺得大家還是注意一下比較好...如果面試官聽到你這樣的回答,可能對你刮目相看,會(huì)認(rèn)為你是一個(gè)對知識極度向往、探索以及有個(gè)人思維想法的學(xué)習(xí)者 ~說白了,就是杠精,這里杠精是褒義詞~
抽象類和接口本質(zhì)區(qū)別
抽象類和接口本質(zhì)區(qū)別主要從語法區(qū)別和設(shè)計(jì)思想兩方面下手
1、語法區(qū)別
1.抽象類可以有構(gòu)造方法,接口中不能有構(gòu)造方法。
2.抽象類中可以有任何類型成員變量,接口中只能有
public static final
變量3.抽象類中可以包含非抽象的普通方法,接口中的可以有非抽象方法,比如
deaflut
方法4.抽象類中的抽象方法的訪問類型可以是
public
,protected
和(默認(rèn)類型,雖然eclipse
下不報(bào)錯(cuò),但應(yīng)該也不行),但接口中的抽象方法只能是public
類型的,并且默認(rèn)即為public abstract
類型。5.抽象類中可以包含靜態(tài)方法,接口中不能包含靜態(tài)方法
6.抽象類和接口中都可以包含靜態(tài)成員變量,抽象類中的靜態(tài)成員變量的訪問類型可以任意,但接口中定義的變量只能是
public static final
類型,并且默認(rèn)即為public static final
類型。7.一個(gè)類可以實(shí)現(xiàn)多個(gè)接口,但只能繼承一個(gè)抽象類。
2、設(shè)計(jì)思想?yún)^(qū)別
對于抽象類,如果需要添加新的方法,可以直接在抽象類中添加具體的實(shí)現(xiàn)(相當(dāng)于寫普通類的普通方法并添加方法體的實(shí)現(xiàn)代碼),子類可以不進(jìn)行變更;而對于接口則不行,如果接口進(jìn)行了變更,則所有實(shí)現(xiàn)這個(gè)接口的類都必須進(jìn)行相應(yīng)的改動(dòng)。這一點(diǎn)應(yīng)該很好理解。
從設(shè)計(jì)角度來講抽象類是對一種對類抽象,抽象類是對整個(gè)類整體進(jìn)行抽象,包括屬性、行為。而接口是對行為的抽象,接口是對類局部(行為)進(jìn)行抽象。從某一角度來講,接口更像是抽象的抽象!
怎么理解上面這段話呢?
理解二者設(shè)計(jì)思想的區(qū)別從程序員宜春和花姑娘(一頭可愛的小母豬)的故事開始,程序員宜春每天過著三點(diǎn)一線的生活,不是吃就是睡覺,閑暇之余還會(huì)敲敲代碼,而花姑娘就厲害了,每天都是一點(diǎn)一線的生活,不是吃就是睡覺,閑暇之余不是吃就是睡覺。程序員宜春和花姑娘都過著幸福安逸的生活,突然有一天,風(fēng)起云涌,天射大便~天色大變~,萬惡的產(chǎn)品經(jīng)理來需求了,要設(shè)計(jì)一個(gè)程序員宜春和花姑娘的一個(gè)程序,要求使用抽象類或者接口去設(shè)計(jì),這個(gè)時(shí)候你會(huì)怎么去設(shè)計(jì),下面給出兩個(gè)設(shè)計(jì)方案...
方案一:使用抽象類設(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è)類繼承抽象類或者實(shí)現(xiàn)上面的接口,都會(huì)出現(xiàn)同樣的狀況:重寫它們的抽象方法。
如果有一百個(gè)程序員宜春,上面的設(shè)計(jì)都是很好地得到解決。但是到花姑娘身上就不管用了,花姑娘不會(huì)敲代碼這種高端操作?。∫话賯€(gè)花姑娘都重寫的qiaoDaiMa
方法都沒有意義啊,顯然這樣設(shè)計(jì)有問題。
從上面可以看出,eat、sleep
對于qiaoDaiMa
方法不是同一范疇內(nèi)的行為(方法)。實(shí)際上我們可以這樣設(shè)計(jì):定義一個(gè)抽象類,包含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è)程序員宜春繼承抽象類并實(shí)現(xiàn)接口就好了,而花姑娘就直接繼承抽象類就好了。這樣一設(shè)計(jì),堪稱完美...
同樣的,這樣講述是很不負(fù)責(zé)的,為啥捏?因?yàn)槟銜?huì)發(fā)現(xiàn),這樣設(shè)計(jì)不管是抽象類還是接口好像沒有什么區(qū)別,剛才的抽象類換成接口,接口換成抽象類,實(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ù)講下去...
我們都知道,可愛的小母豬一般都是粉色的對吧,這個(gè)時(shí)候我們的產(chǎn)品經(jīng)理又改需求了。啥?產(chǎn)品經(jīng)理家中一百只小豬有一只是黑白sai的,額...
萬惡的產(chǎn)品經(jīng)理只會(huì)無理改需求,可是產(chǎn)品經(jīng)理永遠(yuǎn)不會(huì)知道他一味逼程序員,程序員自己都不知道自己有多優(yōu)秀!
我們都知道,可愛的小母豬一般都是粉色的對吧,這個(gè)時(shí)候我們的產(chǎn)品經(jīng)理又改需求了。啥?產(chǎn)品經(jīng)理家中一百只小豬有一只是黑白sai的,額...
萬惡的產(chǎn)品經(jīng)理只會(huì)無理改需求,可是產(chǎn)品經(jīng)理永遠(yuǎn)不會(huì)知道他一味逼程序員,程序員自己都不知道自己有多優(yōu)秀!
那么這個(gè)時(shí)候,我們都知道,抽象類和接口都是可以有成員變量的,只不過接口比較苛刻只能是public static final
正是因?yàn)檫@一點(diǎn)!抽象類和接口的設(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(); }
讓宜春類這樣設(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(); } }
然而宜春對于color
這個(gè)屬性可以是不理睬的,可以當(dāng)做不存在,除非宜春不嫌棄自己也是一只紅sai佩奇哈哈哈....
而花姑娘類就要注意了!然后讓產(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í)候抽象類和接口就不能更換了,從而抽象類和接口的設(shè)計(jì)思想就很清晰了,你何識著咩啊~
本文來自?java入門?欄目,歡迎學(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)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

How to quickly create new emails in Outlook is as follows: 1. The desktop version uses the shortcut key Ctrl Shift M to directly pop up a new email window; 2. The web version can create new emails in one-click by creating a bookmark containing JavaScript (such as javascript:document.querySelector("divrole='button'").click()); 3. Use browser plug-ins (such as Vimium, CrxMouseGestures) to trigger the "New Mail" button; 4. Windows users can also select "New Mail" by right-clicking the Outlook icon of the taskbar
