p504-p505 接口的基础语法
public class interfaceTest {
}
/**
* 1、类和类之间看叫作继承,类和继承之间叫作实现
* 不要多想,可以把“实现”看作“继承”
* 继承使用extends关键字,实现使用implements关键字完成
*2、五颗星(*****)当一个非抽象的方法实现接口的话,必须将家口中的所有的方法全部实现(覆盖、重写)
*/
//特殊的抽象类,完全抽象,又叫接口
interface MyMath{
double PI = 3.1415926;
int sum(int a ,int b);
int sub(int a ,int b);
}
//编写一个类(非抽象的类),类名随意在·
//非抽象的类实现接口时必须重写方法
class MyMathImpl1 implements MyMath{
//重写、实现接口中的方法
public int sum(int a ,int b){
return a + b ;
}
public int sub(int a ,int b){
return a - b ;
}
}
//也可以将类定义为抽象类
abstract class MyMathImpl2 implements MyMath{
}
p506 接口实现和多态
public class interfaceTest {
public static void main(String[] args) {
//使用多态
// 类似于:Animal a = new Animal()
MyMath mm = new MyMathImpl();
//面向接口编程(调用接口中的方法)
int result1 = mm.sum(10,20);
System.out.println(result1);
int result2 = mm.sub(10,20);
System.out.println(result2);
}
}
/**
* 1、类和类之间看叫作继承,类和继承之间叫作实现
* 不要多想,可以把“实现”看作“继承”
* 继承使用extends关键字,实现使用implements关键字完成
*2、五颗星(*****)当一个非抽象的方法实现接口的话,必须将家口中的所有的方法全部实现(覆盖、重写)
*/
//特殊的抽象类,完全抽象,又叫接口
interface MyMath{
double PI = 3.1415926;
int sum(int a ,int b);
int sub(int a ,int b);
}
//编写一个类(非抽象的类),类名随意在·
//非抽象的类实现接口时必须重写方法
class MyMathImpl implements MyMath{
//重写、实现接口中的方法
public int sum(int a ,int b){
return a + b ;
}
public int sub(int a ,int b){
return a - b ;
}
}
//也可以将类定义为抽象类
/*
abstract class MyMathImpl2 implements MyMath{
}*/
p507 一个类实现多个接口
/**
* 1、
*/
public class interfaceTest02 {
public static void main(String[] args) {
//多态使用,都是父类型引用指向子类型对象
A a = new D();
B b = new D();
C c = new D();
//强制转换类型
B b2 = (B)a;
b2.m2();
D d2 = (D)a;
d2.m2();
}
}
interface A{
void m1();
}
interface B{
void m2();
}
interface C{
void m3();
}
class D implements A,B,C{
//实现A接口中的m1
public void m1(){
}
//实现A接口中的m2
public void m2(){
}
//实现A接口中的m3
public void m3(){
}
}
p508 继承和实现同时存在飞猪和飞猫举例
/**
* 1、继承和实现同时存在的话,先写extends,后写implements
*/
public class interfaceTest03 {
public static void main(String[] args) {
Flyable f1 = new Cat();//多态
f1.fly();
Flyable f2 = new Pig();//多态
f2.fly();
Flyable f3 = new Fish();
f3.fly();
}
}
class Animal{
}
interface Flyable{
void fly();
}
//猫
class Cat extends Animal implements Flyable{
public void fly(){
System.out.println("飞猫起飞");
}
}
//蛇类。不想飞就不需要实现Flyable
class Snake extends Animal{
}
//猪类,想飞就插翅膀
class Pig extends Animal implements Flyable{
public void fly(){
System.out.println("飞猪起飞");
}
}
//鱼类,不继承Animal,但是默认继承Object。
class Fish implements Flyable{
public void fly(){
System.out.println("飞鱼起飞");
}
}
p509 总结非抽象类中的基础语法
p510 接口在实际开发中的作用
p511 接口在实际开发中的作用2(从理论上理解)
p512 接口在实际开发中的作用3(举例子理解)
p513 接口在实际开发中的作用4(举例子理解)
p514 接口在实际开发中的作用5(举例子顾客菜单理解)
就是解耦合