2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Why are there interfaces?
As we all know, inheritance is to abstract the common features of subclasses into parent classes,Commonalities of the entire systemTo save code, however, there is also a situation: most subclasses have a commonality, but only a very small number of subclasses do not have this feature. If this commonality is written into the parent class and inherited, it will be unreasonable for these few subclasses.
For example, cats and dogs can swim, but rabbits can't. If we define a "swimming" method in the parent class, it is unreasonable for rabbits to inherit it. However, if cats and dogs write their own swimming methods, the format and naming of the two methods may be inconsistent. Therefore, we need to define a new concept to constrain the writing standards of the "swimming" methods in these two subclasses. At this time, we can define a "swimming" method.interface, define the abstract method swim() in the interface, and then connect the cat and dog to this interface to ensureUnification of code。
To sum up, an interface is arule, when we need to define rules for multiple classes at the same time, we need to useinterface。
An interface does not represent a class of things; an interface representsA rule, so the interface can be passed as an argument to a method.
"No matter if the mover is a truck, a tricycle, or even human labor, as long as he can accomplish the move, he is useful."
搬家(车的对象);
搬家(搬家公司);
public interface 运输 {
...
}
public void 搬家(运输的接口 c) {
...
}
public interface 接口名 {}
public class 类名 implements 接口名 {}
public class 类名 implements 接口名1 , 接口名2 {}
public class 类名 extends 父类 implements 接口名1 , 接口名2 {}
practise: Write standard Javabean classes with interfaces and abstract classes.
青蛙 属性:名字,年龄 行为:吃虫子,蛙泳
狗 属性:名字,年龄 行为:吃骨头,狗刨
兔子 属性:名字,年龄 行为:吃胡萝卜
Write the parent class first. Since the three subclasses eat different things, you can define eat() as an abstract method:
package oopInterface;
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();
}
Write interface Swim:
package oopInterface;
public interface Swim {
public abstract void swim();
}
Write the frog class, pay attention to inheriting the parent class and overriding the abstract method of the parent class, and pay attention to implementing the swimming interface:
package oopInterface;
public class Frog extends Animal implements Swim {
public Frog() {
super();
}
public Frog(String name, int age) {
super(name, age);
}
@Override
public void swim() {
System.out.println("青蛙在蛙泳。");
}
@Override
public void eat() {
System.out.println("青蛙在吃虫子。");
}
}
Write the dog class, pay attention to inheriting the parent class and rewriting the abstract method of the parent class to implement the swimming interface:
package oopInterface;
public class Dog extends Animal implements Swim {
public Dog(){
super();
}
public Dog(String name, int age) {
super(name,age);
}
@Override
public void swim() {
System.out.println("狗在狗刨。");
}
@Override
public void eat() {
System.out.println("狗在吃骨头。");
}
}
Write the Rabbit class. Note that you only need to inherit the parent class and rewrite the abstract method. You do not need to implement the swimming interface (it cannot swim):
package oopInterface;
public class Rabbit extends Animal {
public Rabbit() {
}
public Rabbit(String name, int age) {
super(name, age);
}
@Override
public void eat() {
System.out.println("兔子在吃胡萝卜。");
}
}
Write a test class.
package oopInterface;
public class Test {
public static void main(String[] args) {
Frog f = new Frog("小绿",23);
f.eat();
f.swim();
System.out.println(f.getName() + ", " + f.getAge());
Dog d = new Dog("大D", 24);
d.eat();
d.swim();
System.out.println(d.getName() + ", " + d.getAge());
Rabbit r = new Rabbit("兔子", 30);
r.eat();
System.out.println(r.getName() + ", " + r.getAge());
}
}
Notice:
1. When a class implements an interface, it either implements all the abstract methods in the interface, or the class itself is also an abstract class.
2. A class can implement multiple interfaces. If multiple interfaces are implemented, you need toallTo implement the abstract methods of the interface.
3. Interfaces can inherit multiple interfaces. If a sub-interface inherits multiple interfaces and is then implemented by an implementation class, the implementation class must combine the sub-interface with all its parent interfaces.allAll abstract methods are implemented.
practise: Write standard Javabean classes with interfaces and abstract classes.
乒乓球运动员:姓名,年龄,学打乒乓球,说英语
篮球运动员:姓名,年龄,学打篮球
乒乓球教练:姓名,年龄,教打乒乓球,说英语
篮球教练:姓名,年龄,教打篮球
//Person类
package oopInterExp;
//因为直接创建顶层父类人的对象是没有意义的
//所以将其写为抽象类
public abstract class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
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;
}
}
//Sporter类继承Person
package oopInterExp;
public abstract class Sporter extends Person {
public Sporter(String name, int age) {
super(name, age);
}
public Sporter() {
}
public abstract void learn();
}
//Coach类继承Person
package oopInterExp;
public abstract class Coach extends Person {
public Coach() {
}
public Coach(String name, int age) {
super(name, age);
}
public abstract void teach();
}
//SpeakEnglish接口
package oopInterExp;
public interface SpeakEnglishInter {
public abstract void speakEnglish();
}
//PingPongSporter继承Sporter,实现SpeakEnglish
package oopInterExp;
public class PingPongSporter extends Sporter implements SpeakEnglishInter {
public PingPongSporter(String name, int age) {
super(name, age);
}
public PingPongSporter() {
}
@Override
public void learn() {
System.out.println("学习乒乓球。");
}
@Override
public void speakEnglish() {
System.out.println("乒乓球运动员在说英语。");
}
}
//PingPongCoach继承Coach,实现SpeakEnglish
package oopInterExp;
public class PingPongCoach extends Coach implements SpeakEnglishInter {
public PingPongCoach() {
}
public PingPongCoach(String name, int age) {
super(name, age);
}
@Override
public void teach() {
System.out.println("教乒乓球。");
}
@Override
public void speakEnglish() {
System.out.println("乒乓球教练在说英语。");
}
}
//BasketballSporter继承Sporter
package oopInterExp;
public class BasketballSporter extends Sporter {
public BasketballSporter(String name, int age) {
super(name, age);
}
public BasketballSporter() {
}
public void learn() {
System.out.println("学篮球。");
}
}
//BasketballCoach继承Coach
package oopInterExp;
public class BasketballCoach extends Coach {
public BasketballCoach() {
}
public BasketballCoach(String name, int age) {
super(name, age);
}
public void teach() {
System.out.println("教篮球。");
}
}
Before JDK7, only abstract methods can be defined in an interface.
The new feature of JDK8 is that methods with method bodies can be defined in interfaces (you can definedefaultMethod orStaticmethod).
The new features of JDK9 are: interfaces can be definedprivatemethod.
The method with method body defined in the interface is mainly forInterface upgradeConsider that the interface cannot be static, and new methods need to be added to it for upgrading. If these methods are abstract methods, then the implementation class also needs to implement these methods, which is very troublesome and difficult to synchronize. If the upgrade uses methods with method bodies, then the implementation class does not need to be modified additionally. If modification is required, it can also be modified by rewriting.
Interface Inter1:
package oopInterface5;
public interface Inter1 {
public abstract void method();
public default void default_method() {
System.out.println("Inter1接口中的默认方法");
}
}
Interface Inter2:
package oopInterface5;
public interface Inter2 {
public default void default_method() {
System.out.println("Inter2接口中的默认方法");
}
}
The two default methods have the same name. If the implementation class implements both interfaces at the same time, you must override this default method!
package oopInterface5;
public class InterImpl implements Inter1, Inter2 {
@Override
public void method() {
System.out.println("抽象方法的实现");
}
@Override
public void default_method() {
System.out.println("重写接口中的默认方法");
}
}
Test class:
package oopInterface5;
public class Test {
public static void main(String[] args) {
InterImpl ii = new InterImpl();
ii.method(); //抽象方法的实现
ii.default_method(); //重写接口中的默认方法
}
}
JDK8 and later allow static methods to be defined in interfaces, which need to be modified with static.
InterfaceStatic methodsThe definition format is:
Notes on static methods in interfaces:
Write an interface:
package oopInterface6;
public interface Inter {
public abstract void method();
public static void static_method() {
System.out.println("接口中的静态方法");
}
}
Write an implementation class that also has a static method with the same name as the method in the interface, but this is not an override because static methods cannot be overridden:
package oopInterface6;
public class InteImpl implements Inter {
@Override
public void method() {
System.out.println("重写接口中的抽象方法");
}
//这不叫重写
public static void static_method() {
System.out.println("我不是重写的Inter接口中的静态方法");
}
}
But in fact, the two are different methods.
package oopInterface6;
public class Test {
public static void main(String[] args) {
InteImpl ii = new InteImpl();
ii.method(); //重写接口中的抽象方法
Inter.static_method(); //调用接口中的静态方法
InteImpl.static_method(); //调用实现类中的一个同名的静态方法
}
}
package oopInterface7;
public interface InterA {
public default void show1() {
System.out.println("show1开始执行");
show3();
}
public default void show2() {
System.out.println("show2开始执行");
show3();
}
//普通的私有方法,给默认方法服务的
private void show3() {
System.out.println("记录程序在运行过程中的各种细节,这里有100行代码。");
}
}
package oopInterface7;
public interface InterB {
public static void show1() {
System.out.println("show1开始执行");
show3();
}
public static void show2() {
System.out.println("show2开始执行");
show3();
}
//普通的私有方法,给静态方法服务的
private static void show3() {
System.out.println("记录程序在运行过程中的各种细节,这里有100行代码。");
}
}
1. Interfaces represent rules and are the abstraction of behaviors. If you want a class to have a behavior, just let the class implement the corresponding interface.
2. When a method parameter is an interface, you can pass the interfaceAll objects of the implementing class, this approach is called interface polymorphism.
Adapters can be used to simplify the code and avoid the inconvenience caused by too many abstract methods in the interface and we only need to use some of them.
The general steps for writing are:
1. Write the intermediate class XXXAdapter to implement the corresponding interface.
2. Provide empty implementation for abstract methods in the interface.
3. Let the actual implementation class inherit the intermediate class and rewrite the required methods.
4. In order to avoid other classes from creating objects of the adapter class, the intermediate adapter class is modified with abstract.
interface:
package AdapterDesignPattern;
public interface Inter {
public abstract void method1();
public abstract void method2();
public abstract void method3();
public abstract void method4();
public abstract void method5();
}
Adapter class:
package AdapterDesignPattern;
public abstract class InterAdapter implements Inter {
@Override
public void method1() {
}
@Override
public void method2() {
}
@Override
public void method3() {
}
@Override
public void method4() {
}
@Override
public void method5() {
}
}
Implementation class:
package AdapterDesignPattern;
public class InterImpl extends InterAdapter {
//我需要用到哪个方法,就重写哪个方法就可以了
@Override
public void method5() {
System.out.println("只要用第五个方法");
}
}