Java abstract classes and interfaces

Suunsr 2022-05-22 12:26:20 阅读数:775

javaabstractclassesinterfaces

Catalog

abstract class

One . summary

Interface

1. summary

2. Interface usage principles


abstract class

One . summary

Abstract classes are supersets of ordinary classes , Just more abstract methods than ordinary classes , in real life , There are many abstract classes ( Classes that cannot be mapped to concrete objects ), For example, humans , Animal species .

1. Abstract classes cannot instantiate objects directly , Subclass inherits abstract class , All methods in an abstract class must be overridden ( Subclasses are ordinary classes )

2. utilize abstract Keywords to define abstract classes and abstract methods , The class of the abstract method must be an abstract class , Subclasses must override all abstract methods .

3. Abstract classes must have subclasses ,final and abstract Not at the same time

The greatest significance of abstract classes is to force subclasses to override all abstract methods , Ensure the correct operation of polymorphism . If the subclass is also an abstract class , You don't have to override all abstract methods .

Limitations of abstract classes : The design and implementation are complex .

1. Subclass inherits abstract class , Still satisfied is a principle .

2. Abstract classes are still singleton inheritance limitations , A class can only inherit one abstract class .

Interface

1. summary

An interface is a further step of an abstract class , Abstract classes can also contain non abstract methods and properties , The methods contained in the interface are abstract methods , Attributes can only be static constants .java Use in impls Keyword definition interface .

2. Interface usage principles

1. There is only... In the interface public jurisdiction , There are only global constants and abstract methods in the interface , Inside the interface abstract,static,final,public Can sink slightly !!!

2. Multiple implementations of interfaces , There is no single inheritance limit for interfaces , Subclasses can implement multiple parent interfaces at the same time , When subclasses implement multiple parent interfaces , Use , Separate . Subclasses must implement all abstract methods in the parent interface .

3. The interface still cannot instantiate the object directly , The transformation must be used through sub interfaces .

 4. If the subclass inherits the father at the same time , Implementation interface

Please use first. extends Inherit a father , And then use implemts Implement multiple interfaces . Subclasses implement interfaces without is a principle

is The principle is only to describe the inheritance between classes


copyright:author[Suunsr],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/142/202205211828001185.html