抽象类
被abstract关键字修饰的类,里面有abstract方法
目的
直接贴代码:
public class Person{
void speak(){
symstem.out.println("我是人")
}
}
public class France extends Person{
void speak(){
symstem.out.println("我是法国人")
}
}
public class China extends Person{
void speak(){
symstem.out.println("我是中国人")
}
}
public class American extends Person{
void speak(){
symstem.out.println("我是美国人")
}
}
大家可以看到,中国人、美国人、法国人都继承了Person类,然后重写了speak(),每个人都不同但是又都需要这个方法,所以这里提出用抽象类,继承了抽象类,必须重写它的抽象方法
特点
1.不能创建对象,只能被继承,原因是它存在抽象方法,必须需要实现,不实现它就不是一个具体的类,也就是说你创建的对象必须是一个有具体内容的类的对象。
2.只能被单继承
public abstract class abstractTest {
int num;
abstract void show();//抽象方法
void move() {}//非抽象方法
}
.....
.....
.....
public class abstractTestDemo extends abstractTest{
void show() {}
}
它就拥有了抽象类的抽象和非抽象方法
接口
接口的本质其实是一个特殊的类,它的关键字是interface,方法全部是abstract,变量全部是public static final类型。
目的
解决了类只能被单继承的弊端
特点
1.接口之间可以多继承
2.类可以实现多个接口
3.接口不可以创建对象,里面存在抽象方法
4.变量前面的public static final可以省略,方法前面的abstract可以省略
interface A{
int height;
//public static final int height;
void methodA();
//abstract void method();
}
interface B{
int height;
void methodB();
}
interface C{
int height;
void methodC();
}
interface interTest extends A,B,C{
}
class InterTest implements A,B,C{
void methodA(){}
void methodB(){}
void methodC(){}
}
注意事项
由于JAVA可以多实现接口,就会出现,接口内的方法名相同
interface A{
void int method();
}
interface B{
void boolean method();
}
interface C{
void double method();
}
interface interTest extends A,B,C{
}
class InterTest implements A,B,C{
void int method(){...}
void boolean method(){...}
void double method(){...}
}
InterTest p=new InterTest();
p.method();//调用方法不明确
三个接口中都存在method方法,但是类继承内,我们创建一个对象去调用,会不会出现调用方法不明呢?答案是肯定的,所以实现的方法绝对不允许方法名相同
总结
1.继承是指,类中有具体的方法,我们继承就是可以拿来直接用
2.实现是指类或者对象中有抽象方法,我们必须把方法内容写明确
3.类之间只能单继承,接口之间可以多继承,但是类和接口之间可以多实现
4.抽象类中可以用有抽象方法和非抽象方法,接口只有抽象方法
5.抽象类和接口都不能创建对象,因为存在抽象方法