当前位置:网站首页>Polymorphism and interface
Polymorphism and interface
2022-07-25 14:16:00 【Dumpling_ skin】
1、 polymorphic
The premise of polymorphism is inheritance and method rewriting .
Polymorphism is a characteristic of the ability of parent objects to represent the morphology of multiple subclasses . Polymorphism is when a parent class references a subclass object , Send the same message to different subclasses of the same parent , The behavior is different .
Reasons for using polymorphism : Realize the opening of program design - Closed principle , Open to expansion , Turn off for changes .
Realizing polymorphism :
- Inherit : Subclass inherits parent
- rewrite : Subclass methods override parent methods
- Upward transformation : The parent class reference points to the subclass object
- When calling a method whose parent class is overridden , Different subclasses have different effects .
public class Pet {
protected String name;
protected String color;
public Pet(String name, String color) {
this.name = name;
this.color = color;
}
public void eat(){
System.out.println(" Eat something ");
}
}
public class Cat extends Pet{
public Cat(String name, String color) {
super(name, color);
}
@Override
public void eat() {
System.out.println(this.color+" Of "+this.name+" Eat small fish ");
}
}
public class Dog extends Pet{
public Dog(String name, String color) {
super(name, color);
}
@Override
public void eat() {
System.out.println(this.color+" Of "+this.name+" Eat bones ");
}
}
public class Master {
public void feed(Pet pet){
System.out.println(" The owner feeds the pet ");
pet.eat();
}
}
public class Test {
public static void main(String[] args) {
Pet cat = new Cat(" white "," The small white ");
Pet dog = new Dog(" black "," Little black ");
Master master = new Master();
master.feed(cat);
master.feed(dog);
}
}
2、 Upward transformation / Move down
Upward transformation : Parent class references child class object ( Automatically set up , The disadvantage is the loss of the ability to call methods unique to subclasses )
Move down : Subclasses reference parent objects ( Coercive transformation , Be careful ), Need to use instanceof Make type judgment
public class Master {
public void feed(Pet pet){
System.out.println(" The owner feeds the pet ");
pet.eat();
}
}
public class Test {
public static void main(String[] args) {
Pet p1 = new Cat(" A lot of "," white ");
Pet p2 = new Dog(" Skin and skin "," black ");
Master master = new Master();
master.feed(p1);
master.feed(p2);
if (p1 instanceof Cat){
Cat cat = (Cat) p1;
System.out.println(cat.name+" It's a cute kitten ");
cat.catchMouse();
}
if (p2 instanceof Dog){
Dog dog = (Dog) p2;
System.out.println(dog.name+" It's a cute little dog ");
dog.lookkDoor();
}
}
}3、 abstract class
Keywords for abstract classes :abstract
Abstract classes are generally used as top-level classes ( Parent class ), Inherited by subclasses .
The definition of an abstract class :[ Access modifier ] abstract class Class name {}
Abstract method ( There is no method body , either {}):[ Access modifier ] abstract Return value Method name ();
Characteristics of abstract classes :
- Abstract classes cannot create instance objects , The keyword of an abstract class is abstract;
- Abstract classes can define abstract methods , There can be no abstract methods ;
- Classes with abstract methods must be defined as abstract classes ;
- Instance methods can be defined in abstract classes ;
- Constructors can be defined in abstract classes , The constructor of an abstract class can be called in a subclass ;
- Subclass inherits abstract class , Be sure to rewrite abstract methods , If there is no abstract method that implements the parent class , Then subclasses should also become abstract classes ;
- Abstract methods need to be written before methods abstract keyword , And there can be no method body and {}.
// Defining abstract classes , The class containing abstract methods must be abstract
public abstract class Pet {
protected String name;
protected String color;
public Pet(String name, String color) {
this.name = name;
this.color = color;
}
// Define abstract methods , There can be no method body and {}
public abstract void eat();
}
public class Cat extends Pet{
public Cat(String name, String color) {
super(name, color);
}
// Subclasses must override abstract methods of abstract classes
@Override
public void eat() {
System.out.println(this.name+" Eat small fish ");
}
public void catchMouse(){
System.out.println(this.name+" Catch mice ");
}
}
public class Dog extends Pet{
public Dog(String name, String color) {
super(name, color);
}
@Override
public void eat() {
System.out.println(this.name+" Eat bones ");
}
public void lookDoor(){
System.out.println(this.name+" Can look after the house ");
}
}
public class Test {
public static void main(String[] args) {
Pet p1 = new Cat(" A lot of "," white ");
Pet p2 = new Dog(" toot toot "," black ");
p1.eat();
p2.eat();
if (p1 instanceof Cat){
Cat cat = (Cat) p1;
cat.catchMouse();
}
if (p2 instanceof Dog){
Dog dog = (Dog) p2;
dog.lookDoor();
}
}
}
4、 Interface
Interface is a standard 、 standard ;
On behavior ( Method ) The abstraction of ( Compared with abstract classes , Abstract classes have features and behaviors , Interfaces focus only on behavior );
Is a set of abstract methods ;
Custom rules , Show polymorphism ;
Interface and abstract class have the same status , Exist as the top ( Parent class );
Implementing an interface means having the capabilities represented by the interface .
Interface keywords :interface
Implementation interface :implements
Interface definition format :
[ Permission modifier ] interface The interface name {}
Use steps of interface :
- Methods in the interface cannot be used directly , There must be an implementation class to implement the interface
- The implementation class of the interface must ( Override override ) Implement all abstract methods in the interface
- Create objects that implement classes , Make method calls
The content contained in the interface :
1) Constant
Constants in the interface use public static final Three keywords decorate
public static final AGE = 10;
2) Abstract method
The abstract method in the interface must be decorated with two fixed keywords public abstract. These two keywords can be omitted .
3) The default method
default Enhance the general ability of the interface
default Return value Method name (){}
4) Static methods
Provide a common implementation , Can only be called by interface name , Cannot be called through an implementation class
static Return value Method name (){}
Interface features :
- Interface cannot be instantiated , There can be no way to construct
- The methods in the interface are all abstract methods ,jdk1.8 Then there can be default methods and static methods
- The member variables in the interface use public static final Embellished , And the variable name needs to be capitalized
- Implementation class implementation interface must implement all methods in the interface
- Multiple implementation : A class can implement multiple interfaces
- Interface can inherit interface A extends B
// Interface
public interface Irun {
public abstract void run();
}
// Interface implementation class
public class Falali implements Irun{
@Override
public void run() {
System.out.println(" Ferrari is driving on the road ....");
}
}
public class Baoma implements Irun{
@Override
public void run() {
System.out.println(" BMW is driving on the road ....");
}
}
public class Test {
public static void main(String[] args) {
Irun r1 = new Falali();
Irun r2 = new Baoma();
r1.run();
r2.run();
}
}
5、 The difference between interface and abstract class
Application scenarios : Abstract classes are abstractions of the properties and behaviors of things , accord with is a The relationship between
Interface is an abstraction of behavior , Implementation interface , Have corresponding functions
The same thing : Are top-level parent classes
6、 Comparison of abstract classes and interfaces
7、 Three characteristics of object-oriented
| features | Definition | Realization |
|---|---|---|
| encapsulation | Hide implementation details , Provide public access interface | Privatize properties , Provide public access interface |
| Inherit | Derive a new subclass from a class , Subclasses have non private members in the parent class | Subclass extends Parent class |
| polymorphic | The same method of the parent class will have different implementations in different subclasses | 1、 Inherit 2、 rewrite 3、 Upward transformation |
边栏推荐
- Xintang nuc980 set DHCP or static IP
- Doris learning notes integration with other systems
- Esp32 connects to Alibaba cloud mqtt IOT platform
- Business data analysis of CDA level1 knowledge point summary
- CTS test introduction (how to introduce interface test in interview)
- 【学习记录】plt.show()闪退解决方法
- CDA level Ⅰ 2021 new version simulation question 1 (with answers)
- MySQL table operation
- Gartner 2022 top technology trend: Super automation
- R语言如何将大型Excel文件转为dta格式详解
猜你喜欢

From Anaconda to tensorflow to jupyter, step on the pit and fill it all the way

Working principle of Lora to 4G and gateway repeater

元器件采购系统的主要功能,数字化采购助力元器件企业飞速发展

Mysql表的操作

~5 new solution of CCF 2021-12-2 sequence query

PS制作加载GIF图片教程

用GaussDB(for Redis)存画像,推荐业务轻松降本60%

Hyperautomation for the enhancement of automation in industries

VS2017大型工厂ERP管理系统源码 工厂通用ERP源码

AI model risk assessment Part 1: motivation
随机推荐
金鱼哥RHCA回忆录:CL210管理存储--管理共享文件系统
Mongodb源码部署以及配置
新唐NUC980设置DHCP或者静态IP
手把手教你申请SSL证书
Tm1638 LED digital display module Arduino drive code
idea正则表达式替换(idea正则搜索)
Doris learning notes integration with other systems
Keys and scan based on redis delete keys with TTL -1
用GaussDB(for Redis)存画像,推荐业务轻松降本60%
maya建模练习
Goldfish rhca memoirs: cl210 managing storage -- managing shared file systems
Apple failed to synchronize on its mobile terminal, and logged out. As a result, it could not log in again
thymeleaf通过样式控制display是否显示
Wangeditor rich text editor
Tensorflow2 installation quick pit avoidance summary
Common problems in the use of wireless vibrating wire acquisition instrument
Leetcode 205. isomorphic string (2022.07.24)
Xintang nuc980 set DHCP or static IP
[original] nine point calibration tool for robot head camera calibration
Interpretation of featdepth self-monitoring model for monocular depth estimation (Part I) -- paper understanding and core source code analysis