这是实现抽象的正确方法吗?正如抽象类中的那样
public abstract class Employee {
private String name, address;
int basicSalary;
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public int getbasicSalary(){
return basicSalary;
}
public void setName(String name){
this.name= name;
}
public void setAddress(String address){
this.address= address;
}
public void setBasicSalary(int basicSalary){
this.basicSalary= basicSalary;
}
public abstract int getMonthlySalary();
}
此类扩展了抽象员工类
class NormalEmployee extends Employee {
public NormalEmployee() {
// TODO Auto-generated constructor stub
}
public void setBasicSalary(int basicSalary) {
this.basicSalary=basicSalary;
};
// Method override for salarycalculation
@Override
public int getMonthlySalary() {
// TODO Auto-generated method stub
int monthlySalaryOfNormalEmployee= 1200;
System.out.println("Normal Employee Salary: "+monthlySalaryOfNormalEmployee);
return monthlySalaryOfNormalEmployee;
}
}
public class BonusEmployee extends NormalEmployee {
int bonusAmount;
此类扩展了已从员工类
继承方法的普通员工类 public BonusEmployee() {
// TODO Auto-generated constructor stub
}
public int getBonus(){
return bonusAmount;
}
public static void main(String[] args) {
// Creating objects and calling methods
BonusEmployee bE= new BonusEmployee();
NormalEmployee nE= new NormalEmployee();
bE.setBonus(1200);
bE.setBasicSalary(1500);
bE.getMonthlySalary();
nE.getMonthlySalary();
}
public void setBonus(int bonusAmount){
this.bonusAmount=bonusAmount;
}
@Override
public int getMonthlySalary() {
int getMonthlySalary= basicSalary + getBonus();
System.out.println("Bonus Employee Salary: "+getMonthlySalary);
return basicSalary;
}
}
由于它给我预期的结果所以不知道实施是否正确!
答案 0 :(得分:1)
任何编程语言中的抽象更像是将现实世界的各个方面建模为软件的概念或方法。抽象正在采取一些复杂的东西,并以易于理解或使用的方式在软件中表示,但仍然在现实世界中模拟或保留概念的基本要素。
编写一些代码然后问'我实现了抽象'将取决于你试图在代码中表示的内容。
本文中的软件开发中有一个很好的抽象定义:https://en.wikipedia.org/wiki/Abstraction#In_computer_science