day09-抽象方法和抽象类的使用以及注意事项
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package com.inmind.abstract07;
|
||||
/*
|
||||
当一个方法的具体功能,我们无法实现,那么就不要写方法体,abstract修饰,就是抽象方法
|
||||
拥有抽象方法的类,也就是一个抽象类
|
||||
|
||||
抽象类的格式:
|
||||
public abstract class 类名{
|
||||
public abstract void 方法名(参数列表);
|
||||
}
|
||||
*/
|
||||
//抽象类
|
||||
public abstract class Animal {
|
||||
int age;
|
||||
String name;
|
||||
|
||||
|
||||
public Animal(){
|
||||
System.out.println("抽象类的无参构造执行了");
|
||||
}
|
||||
|
||||
//抽象方法
|
||||
public abstract void eat();
|
||||
/*public abstract void eat1();
|
||||
public abstract void eat2();*/
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.inmind.abstract07;
|
||||
|
||||
public class Cat extends Animal{
|
||||
//对抽象父类的抽象方法进行具体的实现
|
||||
@Override
|
||||
public void eat() {
|
||||
System.out.println("猫吃鱼");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.inmind.abstract07;
|
||||
/*
|
||||
如何使用抽象类和抽象方法???
|
||||
1.抽象类不能被创建对象的,只能通过子类创建对象
|
||||
2.非抽象的子类,必须实现重写抽象类中的抽象方法
|
||||
3.创建子类对象,调用对应方法
|
||||
|
||||
注意事项:
|
||||
1.抽象类不能创建对象,如果创建,编译无法通过而报错。只能创建其非抽象子类的对象。
|
||||
2.抽象类中,可以有构造方法,是供子类创建对象时,初始化父类成员使用的。
|
||||
3.抽象类中,不一定包含抽象方法,但是有抽象方法的类必定是抽象类。
|
||||
4.抽象类的子类,必须重写抽象父类中所有的抽象方法,否则,编译无法通过而报错。除非该子类也是抽象类。
|
||||
*/
|
||||
public class Demo07 {
|
||||
public static void main(String[] args) {
|
||||
//Animal animal = new Animal();
|
||||
//创建抽象类的子类对象
|
||||
Cat cat = new Cat();
|
||||
cat.name = "汤姆";
|
||||
cat.age = 35;
|
||||
cat.eat();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user