第一节 :接口概述
A 对外提供规则的都是接口
B 接口特点
a 接口用关键字 interface表示 interface 接口名字 {}
b 类实现接口 用implements表示
c接口不能实例化 如果想实例化 那么用多态的方式
d 接口的子类 可以是抽象类 没有意义 可以是具体类 需要重写所有的抽象方法
代码是在第九天 重点那个文件夹里
class demo1_interface {
public static void main(String[] args) {
//inter i = new inter(); //接口不能实例化
inter i = new demp();
i.print();
}
}
interface inter
{
public abstract void print();
}
class demp implements inter
{
public void print(){
System.out.println("Hello World!");
}
}
第二节 接口里面的东西
接口中的变量 :都是默认public staic final前缀的
接口中的构造方法:是没有的,如果一个类implements一个接口,它仍然是有构造方法的,extends了一个obj类
接口中的方法:只能是抽象方法,默认是public abstract
class demo2_interface{
public static void main(String[] args) {
demo d = new demo();
d.print();
}
}
interface inter
{
int num = 10;
}
class demo implements inter
{
public void print(){
System.out.println(num);
}
}
第三节 类与接口之间的关系
a 类与类 只能单继承,支持多层继承
b 类与接口
可以实现关系,可以单实现 也可以多实现
可以在继承一个类的时候 同时实现多个接口
c接口与接口
可以单继承 也可以多继承
注意两个问题,一个类实现多个接口的时候,只能写一个implements 第二个问题是接口是可以实例化的
class Demo3_interFace
{
public static void main(String[] args)
{
InterA i = new Demo();
i.printA(); //还能这样 是吧
}
}
interface InterA
{
public abstract void printA();
}
interface InterB
{
public abstract void printB();
}
class Demo implements InterA,InterB
{
public void printA(){
System.out.println("A");
}
public void printB(){
System.out.println("b");
}
}
第四节 抽象类与接口的对比
抽象类: 接口
成员变量 变量、常量 常量
构造方法 有 无
成员方法 抽象、非抽象 抽象
类与类:单继承
类与接口:单实现 多实现
接口与接口 :单继承 多继承
设计理念的区别 :抽象类 is a 接口 like a
第五节 练习
这个是第九节 重点那个文件夹中的demo4
class demo4_interface {
public static void main(String[] args) {
cat c = new cat("加菲",6);
c.eat();
c.sleep();
jumpcat a = new jumpcat("条搞毛",3);
a.eat();
a.sleep();
a.jump();
}
}
abstract class animal
{
private String name;
private int age;
public animal(){}
public animal(String name,int age){
this.name= name;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public abstract void eat();
public abstract void sleep();
}
interface jumping
{
public void jump();
}
class cat extends animal
{
public cat(){}
public cat(String name,int age){
super(name,age);
}
public void eat(){
System.out.println("猫吃鱼");
}
public void sleep(){
System.out.println("侧着睡");
}
}
class jumpcat extends cat implements jumping
{
public jumpcat(){}
public jumpcat(String name,int age){
super(name,age);
}
public void jump(){
System.out.println("猫调高");
}
}
最后还有一节视频 是一个练习 自己没写