抽象类的应用

-------------siwuxie095

   

   

   

   

抽象类的应用:

   

代码:

   

package com.siwuxie095.abs;

   

//父类 Person 抽象类

abstract class Person{

private String name;

private int age;

 

//构造方法

public Person(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;

}

 

//抽象方法

abstract void want();

 

}

   

//子类 Student

class Student extends Person{

private int score;

 

public int getScore() {

return score;

}

   

public void setScore(int score) {

this.score = score;

}

   

//复写构造方法,因为父类存在构造方法

public Student(String name, int age,int score) {

super(name, age);

this.score=score;

}

 

//复写抽象方法

void want() {

System.out.println("姓名:"+getName()+" 年龄:"+getAge()+" 成绩:"+getScore());

}

 

 

}

   

//子类 Worker

class Worker extends Person{

private int money;

 

public int getMoney() {

return money;

}

   

public void setMoney(int money) {

this.money = money;

}

   

public Worker(String name, int age,int money) {

super(name, age);

this.money=money;

}

 

@Override

void want() {

System.out.println("姓名:"+getName()+" 年龄:"+getAge()+" 工资:"+getMoney());

}

 

}

   

public class AbstractDemo01 {

   

public static void main(String[] args) {

//如果有其他的分类,如 Teacher 同样可以继承自抽象类 Person

//无论什么时候都不要去继承一个已经完成好的类

Student s=new Student("小明", 10, 100);

s.want();

Worker w=new Worker("大明", 30, 10000);

w.want();

 

 

}

   

}

   

   

运行一览:

   

   

   

   

   

【made by siwuxie095】

原文地址:https://www.cnblogs.com/siwuxie095/p/6575358.html