Java链式写法,子类继承父类的属性,也可以返回子类的对象,只是需要重写基类的Set方法
public class MyLS { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(new Student().setName("1").setAge(21).toString()); System.out.println(new NAN().setName("2").setAge(20).setSex('男').toString()); System.out.println(new NV().setName("3").setAge(22).setSex('女').toString()); }}class Student{ private String name; private Integer age; public String getName() { return name; } public Student setName(String name) { this.name = name; return this; } public Integer getAge() { return age; } public Student setAge(Integer age) { this.age = age; return this; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", getName()=" + getName() + ", getAge()=" + getAge() + "]"; } }class NAN extends Student{ private Character sex='男'; public Character getSex() { return sex; } public NAN setSex(Character sex) { this.sex = sex; return this; } @Override public NAN setName(String name) { super.setName(name); return this; } @Override public NAN setAge(Integer age) { // TODO Auto-generated method stub super.setAge(age); return this; } @Override public String toString() { return "NAN [sex=" + sex + ", getSex()=" + getSex() + ", getName()=" + getName() + ", getAge()=" + getAge() + "]"; } }class NV extends Student{ private Character sex='女'; public Character getSex() { return sex; } public NV setSex(Character sex) { this.sex = sex; return this; } @Override public NV setName(String name) { super.setName(name); return this; } @Override public NV setAge(Integer age) { // TODO Auto-generated method stub super.setAge(age); return this; } @Override public String toString() { return "NV [sex=" + sex + ", getSex()=" + getSex() + ", getName()=" + getName() + ", getAge()=" + getAge() + "]"; } }