当前位置:网站首页>Abstract classes and interfaces
Abstract classes and interfaces
2022-06-30 09:40:00 【Wang Xiaoya】
1. abstract class
1.1 An overview of abstract classes ( understand )
When we do subclass common function extraction , Some methods are not embodied in the parent class , At this time, we need abstract classes !
stay Java in , One There is no method body Of Method Should be defined as Abstract method , In the class, if There are abstract methods , The class must be defined as abstract class !
1.2 Characteristics of abstract classes ( memory )
Abstract classes and abstract methods must use abstract Keyword modification
// The definition of an abstract class public abstract class Class name {} // Definition of abstract method public abstract void eat();
There is not necessarily an abstract method in an abstract class , A class with abstract methods must be an abstract class
Abstract class cannot be instantiated
How to instantiate an abstract class ? Refer to polymorphic ways , Instantiation through subclass objects , This is called abstract class polymorphism
A subclass of an abstract class
Or rewrite all the abstract methods in the abstract class
Or an abstract class
1.3 Member characteristics of abstract classes ( memory )
The characteristics of the members
Member variables
It can be a variable
It can also be a constant
Construction method
Space parameter structure
There are parametric structures
Member method
Abstract method
Common method
Member characteristics of abstract classes
Member variables
- It can be a variable or a constant
Construction method
There's a way to structure , But you can't instantiate
that , What is the function of the construction method ? Initialization member method for subclass to access parent class data
Member method
There can be abstract methods : A qualified subclass must perform certain actions
There can also be non abstract methods : Improve code reusability ( Implemented by inheritance )
Code demonstration
package com.object_03; // abstract class public abstract class Animal1 { private int age = 20; private final String city = " Beijing "; public Animal1() {} public Animal1(int age) { this.age = age; } public void show() { age = 40; System.out.println(age); System.out.println(city); } // Abstract method public abstract void eat(); } package com.object_03; public class Cat1 extends Animal1{ @Override public void eat() { System.out.println(" Cats eat fish "); } } package com.object_03; // abstract class public abstract class Animal1 { private int age = 20; private final String city = " Beijing "; public Animal1() {} public Animal1(int age) { this.age = age; } public void show() { age = 40; System.out.println(age); System.out.println(city); } // Abstract method public abstract void eat(); }
1.4 Examples of abstract classes ( application )
Case needs
Please use the idea of abstract class to realize the case of cat and dog , And test in the test class
Ideas :
1. Define animals (Animal)
Member variables : full name , Age structure method : No arguments , Banded ginseng
Member method : get/set Method , having dinner ;
2. Define cats (Cat), Inherit the animal class
Construction method : No arguments , Members with parameters
Method : Rewrite dinner (){.….}
3. Define dogs (Dog), Inherit the animal class
Construction method : No arguments , Banded ginseng
Member method : Rewrite dinner ({.….}
4. Define test classes (AnimalDemo), Write code test
Code implementation
package com.object_03; // Examples of abstract classes public abstract class Animal2 { private String name; private int age; public Animal2() { } public Animal2(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public abstract void eat(); } package com.object_03; public class Dog2 extends Animal2 { public Dog2() { } public Dog2(String name, int age) { super(name, age); } @Override public void eat() { System.out.println(" Dogs eat bones "); } } package com.object_03; public class Cat2 extends Animal2 { public Cat2() { } public Cat2(String name, int age) { super(name, age); } @Override public void eat() { System.out.println(" Cats eat fish "); } } package com.object_03; public class AnimalDemo2 { public static void main(String[] args) { // Create objects , In a polymorphic way Animal2 a = new Cat2(); a.setName(" Siam "); a.setAge(6); System.out.println(a.getName()+","+a.getAge()); a.eat(); System.out.println("*****************"); a =new Cat2(" Chinese country cat ",5); System.out.println(a.getName()+","+a.getAge()); a.eat(); } }
1.5 The difference between abstract classes and interfaces
Examples of doors and alarms
door : There are open) and close() Two actions , This is the time , We can use abstract classes and interfaces to define this abstract concept
abstract class
// abstract class
public abstract class Door {
public abstract void open ( ) ;
public abstract void close ( ) ;
public abstract void alarm ( ) ; // But some doors have no alarm function
}
Interface
// Interface
public interface Door {
void open ( ) ;
void close () ;
void alarm(); // But the access interface will also realize open and close
}
Improvement :
public interface Alram {void alarm () ;
}
public abstract class Door {
public abstract void open ( ) ;public abstract void close ( );}
public class AlarmDoor extends Door implements Alarm {
public void oepn () {
// ....
}
public void close (o) {l l ....
}
public void alarm () {
// ....
}
}
Here we will alarm Implemented separately as an interface , Write when necessary , Just be independent
ad locum , We emphasize again that abstract classes are abstractions of things , And interfaces are abstractions of behavior
2. Interface
2.1 Overview of interface ( understand )
Interface is a kind of public standard , As long as it conforms to the standard , Everyone can use it .
Java The interface in is more embodied in the abstraction of behavior !
2.2 Interface features ( memory )
Interface with keywords interface modification
public interface The interface name {}
Class to implement the interface implements Express ( Inheritance cannot be used between classes and interfaces , need implements( Realization ) To connect )
public class Class name implements The interface name {}
Interface cannot be instantiated
How to instantiate an interface ? Refer to polymorphic ways , By implementing class object instantiation , This is called interface polymorphism .
package com.itheima_o1; /* Test class */ public class JumppingDemo i public static void main( String[] args) { //Jumpping j = new Jumpping(); // failed , Interface cannot be instantiated // How to instantiate an interface ? Refer to polymorphic ways , By implementing class object instantiation , This is called interface polymorphism Jumpping j = new Cat(); j.jump(); } }
Polymorphic forms : Concrete class polymorphism , Abstract class polymorphism , Interface polymorphism .
The premise of polymorphism : Having a relationship of inheritance or realization ; There's a way to rewrite ; Have a father ( class / Interface ) Reference point ( Son / Realization ) Class object
Implementation class of interface
Or rewrite all abstract methods in the interface
Either subclasses are abstract classes
2.3 Member characteristics of the interface ( memory )
Member characteristics
Member variables
It can only be constant Default modifier :public static final
Construction method
Interface has no constructor , Because the interface is mainly to abstract the behavior , There is no concrete existence
If a class has no parent class , Default inherited from Object class
Member method
Only abstract methods
Default modifier :public abstract
About the methods in the interface ,JDK8 and JDK9 There are some new features in , I'll explain later
Code demonstration
public interface Inter { public int num = 10; // There are member variables public final int num2 = 20; // It can be a constant // public static final int num3 = 30; int num3 = 30; // public Inter() {} // public void show() {} // Interfaces are abstract methods , There can be no method {} public abstract void method(); void show(); } public class InterImpl extends Object implements Inter { // Interface implementation class naming , Class name +Impl public InterImpl() { super(); } @Override public void method() { System.out.println("method"); } @Override public void show() { System.out.println("show"); } } public class InterfaceDemo { public static void main(String[] args) { Inter i = new InterImpl(); // By creating objects // i.num = 20; System.out.println(i.num); // i.num2 = 40; System.out.println(i.num2); System.out.println(Inter.num); } }
Interface
Implementation class
Test class
2.4 Interface case ( application )
Case needs
Train cats and dogs , They can jump high , Add the high jump function here .
Please use abstract classes and interfaces to implement the cat and dog case , And test in the test class .
Code implementation
Animal species
package com.object_04.interface_01; public abstract class Animal { private String name; private int age; public Animal() { } public Animal(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } // public void setAge(int age) { // this.age = age; // } // public abstract void eat(); public void setAge(int age) { this.age = age; } public abstract void eat(); }
High jump interface
package com.object_04.interface_01; // High jump interface public interface Jumpping { public abstract void jump(); }
Cats
package com.object_04.interface_01; public class Cat extends Animal implements Jumpping { public Cat() { } public Cat(String name, int age) { super(name, age); } @Override public void eat() { System.out.println(" Cats eat fish "); } @Override public void jump() { System.out.println(" The cat can jump high "); } }
Test class
package com.object_04.interface_01; public class AnimalDemo { public static void main(String[] args) { // Create objects , Calling method Jumpping j = new Cat(); j.jump(); System.out.println("--------"); Animal a = new Cat(); a.setName(" Garfield "); a.setAge(5); System.out.println(a.getName()+","+a.getAge()); a.eat(); // a.jump(); a = new Cat(" Garfield ",5); System.out.println(a.getName()+","+a.getAge()); a.eat(); System.out.println("--------"); Cat c = new Cat(); c.setName(" Garfield "); c.setAge(5); System.out.println(c.getName()+","+c.getAge()); c.eat(); c.jump(); } } package com.object_04.interface_01;
result :
The cat can jump high -------- Garfield ,5 Cats eat fish Garfield ,5 Cats eat fish -------- Garfield ,5 Cats eat fish The cat can jump high
2.5 The relationship between class and interface ( memory )
The relationship between class and class
Inheritance relationships , Only inheritance , But you can inherit more than one
The relationship between class and interface
Realization relationship , It can be realized by itself , It can also be realized more , You can also implement multiple interfaces while inheriting a class
The relationship between interface and interface
Inheritance relationships , Can inherit alone , You can also inherit more
2.6 The difference between abstract classes and interfaces ( memory )
Member differences
abstract class
Variable , Constant ; There's a way to structure ; There are abstract methods , There are also non abstract methods
Interface
Constant ; Abstract method
Relationship difference
Class and class
Inherit , Single inheritance
Classes and interfaces
Realization , It can be realized by itself , It can also be realized more
Interface and interface
Inherit , Single inheritance , Multiple inheritance
Design concept difference
abstract class
Abstract classes , Including attributes 、 Behavior
Interface
Abstract behavior , Mainly behavior
3. Comprehensive case
3.1 Case needs ( understand )
We now have table tennis players and basketball players , Table tennis coaches and basketball coaches .
In order to go abroad to exchange , People related to table tennis need to learn English .
Please use what you have learned to analyze , What specific classes are there in this case , Which abstract classes , Which interfaces , And implement it in code .
3.2 Code implementation ( application )
Abstract human
public abstract class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public abstract void eat();
}
Abstract athlete class
public abstract class Player extends Person {
public Player() {
}
public Player(String name, int age) {
super(name, age);
}
public abstract void study();
}
Abstract coach class
public abstract class Coach extends Person {
public Coach() {
}
public Coach(String name, int age) {
super(name, age);
}
public abstract void teach();
}
Learn English interface
public interface SpeakEnglish {
public abstract void speak();
}
Basketball coach
public class BasketballCoach extends Coach {
public BasketballCoach() {
}
public BasketballCoach(String name, int age) {
super(name, age);
}
@Override
public void teach() {
System.out.println(" The basketball coach teaches how to dribble and shoot ");
}
@Override
public void eat() {
System.out.println(" Basketball coaches eat mutton , Drink goat's milk ");
}
}
Table tennis coach
public class PingPangCoach extends Coach implements SpeakEnglish {
public PingPangCoach() {
}
public PingPangCoach(String name, int age) {
super(name, age);
}
@Override
public void teach() {
System.out.println(" The table tennis coach teaches how to serve and receive the ball ");
}
@Override
public void eat() {
System.out.println(" The table tennis coach eats cabbage , Drink rice porridge ");
}
@Override
public void speak() {
System.out.println(" The table tennis coach speaks English ");
}
}
Table tennis players
public class PingPangPlayer extends Player implements SpeakEnglish {
public PingPangPlayer() {
}
public PingPangPlayer(String name, int age) {
super(name, age);
}
@Override
public void study() {
System.out.println(" Table tennis players learn how to serve and receive ");
}
@Override
public void eat() {
System.out.println(" Table tennis players eat Chinese cabbage , Eat rice porridge ");
}
@Override
public void speak() {
System.out.println(" Table tennis players speak English ");
}
}
Basketball players
public class BasketballPlayer extends Player {
public BasketballPlayer() {
}
public BasketballPlayer(String name, int age) {
super(name, age);
}
@Override
public void study() {
System.out.println(" Basketball players learn how to dribble and shoot ");
}
@Override
public void eat() {
System.out.println(" Basketball players eat beef , Drink milk ");
}
}
4. Parameter passing
4.1 Class name as formal parameter and return value ( application )
1、 The class name is used as the formal parameter of the method
The formal parameter of the method is the class name , In fact, what you need is the object of this class
What is actually passed is the... Of the object 【 Address values 】
2、 The class name is used as the return value of the method
The return value of the method is the class name , In fact, it returns the object of this class
Actually delivered , Is also the of the object 【 Address values 】
Sample code :
class Cat { public void eat() { System.out.println(" Cats eat fish "); } } class CatOperator { public void useCat(Cat c) { //Cat c = new Cat(); c.eat(); } public Cat getCat() { Cat c = new Cat(); return c; } } public class CatDemo { public static void main(String[] args) { // Create an operation class object , And call methods CatOperator co = new CatOperator(); Cat c = new Cat(); co.useCat(c); Cat c2 = co.getCat(); //new Cat() c2.eat(); } }
4.2 Abstract classes as formal parameters and return values ( understand )
Abstract classes as formal parameters and return values
The formal parameter of the method is the abstract class name , In fact, what is needed is the subclass object of the abstract class
The return value of the method is the abstract class name , In fact, it returns the subclass object of the abstract class
Sample code :
abstract class Animal { public abstract void eat(); } class Cat extends Animal { @Override public void eat() { System.out.println(" Cats eat fish "); } } class AnimalOperator { public void useAnimal(Animal a) { //Animal a = new Cat(); a.eat(); } public Animal getAnimal() { Animal a = new Cat(); return a; } } public class AnimalDemo { public static void main(String[] args) { // Create an operation class object , And call methods AnimalOperator ao = new AnimalOperator(); Animal a = new Cat(); ao.useAnimal(a); Animal a2 = ao.getAnimal(); //new Cat() a2.eat(); } }
4.3 Interface name as formal parameter and return value ( understand )
Interface as a formal parameter and return value
The formal parameter of the method is the interface name , What we need is the implementation class object of the interface
The return value of the method is the interface name , In fact, it returns the implementation class object of the interface
Sample code :
interface Jumpping { void jump(); } class JumppingOperator { public void useJumpping(Jumpping j) { //Jumpping j = new Cat(); j.jump(); } public Jumpping getJumpping() { Jumpping j = new Cat(); return j; } } class Cat implements Jumpping { @Override public void jump() { System.out.println(" The cat can jump high "); } } public class JumppingDemo { public static void main(String[] args) { // Create an operation class object , And call methods JumppingOperator jo = new JumppingOperator(); Jumpping j = new Cat(); jo.useJumpping(j); Jumpping j2 = jo.getJumpping(); //new Cat() j2.jump(); } }
边栏推荐
- Couldn't load this key (openssh ssh-2 private key (old PEM format))
- utils session&rpc
- ABAP-时间函数
- Flutter 0001, environment configuration
- thrift简单使用
- Application of hongruan face recognition
- Script summary
- 布隆过滤器
- ES6 learning road 5 symbol
- Acquisition de 100% des actions de Guilin latex par Guilin Robust Medical pour combler le vide de la gamme de produits Latex
猜你喜欢
MySQL index and data storage structure foundation
float
【新书推荐】Cleaning Data for Effective Data Science
Harmonyos actual combat - ten thousand words long article understanding service card development process
Numpy (time date and time increment)
What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?
Applet learning path 2 - event binding
ES6 learning path (II) let & const
JVM tuning tool commands (notes)
八大排序(一)
随机推荐
小程序手持弹幕的原理及实现(uni-app)
Baidu map JS browsing terminal
抽象类和接口
Net framework system requirements
近期学习遇到的比较问题
Tclistener server and tcpclient client use -- socket listening server and socketclient use
Flutter theme (skin) changes
I'm late for school
prometheus 监控之 ntp_exporter
ES6 learning path (III) deconstruction assignment
float
Self service terminal handwritten Chinese character recognition input method library tjfink introduction
3.集成eslint、prettier
AutoUpdater. Net client custom update file
Experience of an acmer
直播带货源码开发中,如何降低直播中的延迟?
Handwriting sorter component
MySQL explain
9.JNI_ Necessary optimization design
Self service terminal development process