关闭

Review-Java基础--抽象类(abstract)

标签: 对象继承抽象类
157人阅读 评论(0) 收藏 举报
分类:

抽象类不能被实例化,即如果将一个类声明为abstract,就不能创建这个类的对象。但可以创建一个具体的子类的对象。
另外:可以根据抽象类,可以定义一个抽象类的对象变量,但它只能引用非抽象子类的对象。
假设Person为一个抽象类,Sudent为一个继承自Person的非抽象子类。则Person p=new Person(“name”);当然了这事一个错误的写法
但可以创建一个具体子类的对象
Person p=new Student(“name”);
p为抽象类Person的变量,Person引用了一个非抽象子类Student的实例

package abstractClassess;

import javax.swing.text.StyledEditorKit.ForegroundAction;

/**
 * This program demonstracts abstract classes;
 * 
 * @version 2016-08-29
 * @author Administrator
 *
 */
public class PersonTest {

    public static void main(String[] args) {
        Person[] person = new Person[2];
        //抽象类不能实例化
        person[0] = new Employee("张三", 3728, 1293, 20, 2);
        person[1] = new Student("小明", "Computer Science And Technology");
        for (Person people : person) {
            System.out.println(people.getName() + "," + people.getDescription());
        }
    }

}
package abstractClassess;

public abstract class Person {


    /* 抽象方法充当占位作用,具体实现在子类中*/
    public abstract String getDescription();

    private String name;

    public Person(String name)
    {
        this.name=name;
    }
    public String getName()
    {
        return name;
    }

}
package abstractClassess;

public class Student extends Person{

    private String major;
    public Student(String name,String major){
        super(name);

        this.major=major;
    }
    public String getDescription()
    {
        return ("a student majoring in "+major);
    }
}
package abstractClassess;

import java.util.Date;
import java.util.GregorianCalendar;

public class Employee extends Person{

    private double salary;
    private Date hireDay;
    public Employee(String name,double s,int year,int month,int day) {
        super(name);
        // TODO Auto-generated constructor stub
        this.salary=s;
        GregorianCalendar calender=new GregorianCalendar(year,month-1,day);
        hireDay=calender.getTime();

    }

    public double getSalary()
    {
        return salary;
    }
    public Date getHireDay()
    {
        return hireDay;
    }
    @Override
    public String getDescription() {
        // TODO Auto-generated method stub
        return String.format("an employee with a salary of $%.2f", salary);
    }

    public void raiseSalary(double byPercent)
    {
        double raise=salary * byPercent/100;
        salary+=raise;
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:20219次
    • 积分:1000
    • 等级:
    • 排名:千里之外
    • 原创:81篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条