抽象类和抽象方法的定义格式
抽象类和抽象方法的注意事项
抽象类的构造方法的作用:当创建子类对象时,给属性进行赋值
抽象类的作用:抽取共性时,无法确定方法体,就把方法定义为抽象的。强制让子类按照某种格式重写,抽象方法所在的类必须是抽象类
- package com.itheimaabstract;
-
- 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 void drink(){
- System.out.println("喝水");
- }
-
- public abstract void eat();
- }
- package com.itheimaabstract;
-
- public class Frog extends Animal {
-
- public Frog() {
- }
-
- public Frog(String name, int age) {
- super(name, age);
- }
-
- @Override
- public void eat() {
- System.out.println("青蛙吃虫子");
- }
- }
- package com.itheimaabstract;
-
- public class Dog extends Animal {
- public Dog() {
- }
-
- public Dog(String name, int age) {
- super(name, age);
- }
-
- @Override
- public void eat() {
- System.out.println("修狗吃骨头");
- }
- }
- package com.itheimaabstract;
-
- public class Sheep extends Animal {
- public Sheep() {
- }
-
- public Sheep(String name, int age) {
- super(name, age);
- }
-
- @Override
- public void eat() {
- System.out.println("羊吃草");
- }
- }
- package com.itheimaabstract;
-
- public class Test {
- public static void main(String[] args) {
- Frog f=new Frog("小绿",3);
- System.out.println(f.getName() +","+f.getAge() );
- f.drink() ;
- f.eat() ;
- Dog d=new Dog("小黄",3);
- System.out.println(d.getName() +","+d.getAge());
- d.drink() ;
- d.eat() ;
- Sheep s=new Sheep("小黑",2);
- System.out.println(s.getName() +","+s.getAge());
- s.drink() ;
- s.eat() ;
- }
- }
运行结果: