欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

抽象类abstract

程序员文章站 2022-04-01 10:15:43
...

我们先来看一下Person类和子类的继承图,我们可以声明一个Person的父类,然后让它的子类派生,因为它的子类各有不同的属性和参数,所以为Person类实例方法显得有些浪费内存,这样,我们可以使用abstract关键字进行声明,这样就完全可以不需要实现这个方法了。

抽象类abstract

为了提高程序的清晰度,包含一个或多个抽象方法本身必须被声明为抽象的。

建议大家在抽象类中不要包含具体方法,尽量将通用的域和方法放在超类里。

抽象类不可悲被实例化,并且,继承他的子类必须实现父类的抽象方法定义。

package abstractClasses;

public class PersonTest {

	public static void main(String[] args) {
		Person[] people = new Person[2];
		
		people[0] = new Employee("Harry Hacker", 50000 , 1989, 10, 1);
		people[1] = new Student("Maria Morris", "computer science");
		
		for(Person p : people) {
			System.out.println(p.getName() + "," +p.getDescription());
		}
	}

}
package abstractClasses;

public abstract class Person {
	public abstract String getDescription();
	private String name;
	public Person(String name) {
		super();
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}
package abstractClasses;
import java.time.*;
public 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;
		this.hireDay = LocalDate.of(year, month, day);
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public LocalDate getHireDay() {
		return hireDay;
	}
	public void setHireDay(LocalDate hireDay) {
		this.hireDay = hireDay;
	}
	@Override
	public String getDescription() {
		
		return String.format("an employee with a salary of $%.2f",salary);
	}
	
	public void raiseSalary(double byPercent) {
		double raise = salary * byPercent / 100;
		salary += raise;
	}
	
	
	
	
	
	
}
package abstractClasses;

public class Student extends Person {
	private String major;

	public Student(String name, String major) {
		super(name);
		this.major = major;
	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return "a student maroring in" + major;
	}	
}

 

相关标签: abstract