首页 > 代码库 > 多态性的使用
多态性的使用
public class Department { public String name; private int number; public Department() { super(); } public Department(String name, int number) { super(); this.name = name; this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public void business(){ System.out.println("为集团引进IT设备"); } public int aveSalary(int sum){ System.out.println("部门平均薪水"+sum); return sum; }
public class SoftDep extends Department { private boolean programming; public SoftDep() { super(); } public SoftDep(boolean programming) { super(); this.programming = programming; } public boolean isProgramming() { return programming; } public void setProgramming(boolean programming) { this.programming = programming; } public void business(){ System.out.println("为集团引进软件和系统"); } public int aveSalary(int sum){ System.out.println("薪水较高"); return sum; } public void future(){ System.out.println("前景较好"); }
package lianxi2;public class HardDep extends Department { private boolean communicate; public boolean isCommunicate() { return communicate; } public void setCommunicate(boolean communicate) { this.communicate = communicate; } public HardDep() { super(); } public HardDep(boolean communicate) { super(); this.communicate = communicate; } @Override public int aveSalary(int sum) { System.out.println("薪水较低"); return sum; } @Override public void business() { System.out.println("负责引进硬件设施和网络"); } public void future(){ System.out.println("前景堪忧"); }}
package lianxi2;public class TestDep { public static void main(String[] args) { TestDep t = new TestDep(); Department d = new Department("信息中心",001); //d.name; --------------只是一个属性不能作为语句,调用一个方法可以 System.out.println(d.name); System.out.println(d.getName()); System.out.println(d.getNumber()); d.business(); System.out.println(d.aveSalary(4000)); Department d1 = new SoftDep(true); //向上转型,只能调用子类中重写父类的方法 if(d1 instanceof SoftDep){ // System.out.println(d1.isProgramming()); ---------------属性没有多态性 System.out.println(d1.aveSalary(5000)); d1.business(); SoftDep so = (SoftDep)d1; //向下转型,可以调用所有子类中的方法 System.out.println("$"+so.aveSalary(5000)); so.future(); System.out.println(so.isProgramming()); t.func(new SoftDep()); } System.out.println("\n\n"); t.func(new HardDep()); } public void func(Department d3){ d3.business(); System.out.println(d3.aveSalary(6000)); if(d3 instanceof HardDep){ HardDep hd = (HardDep)d3; hd.future(); } if(d3 instanceof SoftDep){ SoftDep so = (SoftDep)d3; so.future(); } }}
多态性的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。