简介
java 中的抽象类学习
code
main
package com;
public class PersonTest {
public static void main(String[] args) {
Person[] person = new Person[2];
person[0] = new Employee("Harry Hacker", 5000, 1989, 10,1);
person[1] = new Student("Maria Morris", "computer science");
for(Person p : person)
System.out.println(p.getName() + ", " + p.getDescription());
}
}
abstract
package com;
public abstract class Person {
public abstract String getDescription();
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Student
package com;
public class Student extends Person{
private String major;
/**
* @param name the student's name
* @param major the student's major
*/
public Student(String name, String major) {
super(name);
this.major = major;
}
public String getDescription(){
return "a student majoring in " + major;
}
}
Employee
package com;
import java.util.Random;
import java.time.*;
class Employee extends Person{
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day){
super(name);
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public double getSalary() {
return salary;
}
public LocalDate getHireDay() {
return hireDay;
}
public String getDescription() {
return String.format("an emplyee with a salary of $%.2f", salary);
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent / 100;
salary += raise;
}
}
自问自答环节
QU: 抽象类能不能生成对象
AN:不能
QU:某类继承了抽象类,在什么情况加某类才不是抽象类
AN:实现了抽象类里面的函数覆盖
---------------------------我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去。
--------《白夜行》