标签:person 不同的 哪些 super关键字 for 除了 构造 eth 封装
private int age; public void setAge( int age) { if (age>0&&age<100) { this.age=age; }else { System.out.println("输入年龄不合法"); this.age=-1; } } public int getAge() { return this.age; }
并且可以在set方法中设置判断条件,例如上例就是判断年龄是否符合常识
②提高代码的维护性。
③将类与类联系起来,是多态的前提。
public class a; public class a2 extends a; public class a3 extends a2;
此时,a3就得到了a和a2两个类的非私有属性
Chinese c=new chinese(); c.say(); english e=new english(); e.say();
英国人说英语,中国人说中文 这不叫多态
person p=new chinese(); p.say(); person p=new english(); p.say();
同样是人 有人说英语,有人说中文 这叫多态
建一个父类(Instrument类 Instrument类有两个属性:品牌(brand)、重量(weight)以及一个抽象方法:弹奏( play )方法)
public abstract class Instrument{ private String brand; private String weight; public abstract void play(); public Instrument() { super(); } public Instrument(String brand, String weight) { super(); this.brand = brand; this.weight = weight; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } }
建两个子类(钢琴(Piano)、小提琴(Violin))
钢琴(Piano)类中有私有属性尺寸(size)
public class Piano extends Instrument{ private String size;
public String getSize() { return size; } public void setSize(String size) { this.size = size; }
public Piano(String size) { super(); this.size = size; } public Piano() { super(); } @Override public void play() { // TODO Auto-generated method stub System.out.println("演奏家弹钢琴");
} }
小提琴(Violin)类中有私有属性长度(length)
public class Violin extends Instrument { private String length; public String getLength() { return length; } public void setLength(String length) { this.length = length; } public Violin(String length) { super(); this.length = length; } public Violin() { super(); } @Override public void play() { // TODO Auto-generated method stub System.out.println("演奏家拉小提琴");
} }
建一个多态类
演奏家 (演奏方法)
public class Performer { public void make(Instrument p) { p.play(); }
}
最后建一个测试类
public static void main(String[] args) { Performer t=new Performer(); t.make(new Piano()); t.make(new Violin()); }
运行结果为:
标签:person 不同的 哪些 super关键字 for 除了 构造 eth 封装
原文地址:https://www.cnblogs.com/fylong/p/8745991.html