类之间的相互引用
class Car { private String name; private double price; private Person person;
public Car (String name , double price){ this.name = name ; this.price = price; }
public void setPerson(Person p){ this.person = p; }
public Person getPerson(){42 collapsed lines
return this.person; }
public String getInfo(){ return "car name :" +this.name +", car price: " + this.price; }}
class Person{ private String name; private int age; private Car car;
public Person(String name , int age){ this.name= name ; this.age = age; }
public void setCar(Car car){ this.car = car; }
public Car getCar(){ return this.car; }
public String getInfo(){ return "person name :" +this.name+", person age:" +this.age; }}public class ArrayDemo{ public static void main(String args []){
Person p1 =new Person("cirry", 18); Car c1 =new Car("audi", 400000); p1.setCar(c1); c1.setPerson(p1);
System.out.println(p1.getCar().getInfo()); System.out.println(c1.getPerson().getInfo()); }}两个类的互相引用和配置
class Dept{ private String name; private String loc; private Emp emps []; // 所有员工
public Dept(String name , String loc){ this.name = name ; this.loc = loc; }
public void setEmps(Emp [] emps){ this.emps = emps; }
public Emp [] getEmps(){60 collapsed lines
return this.emps; }
public String getInfo(){ return "dept name:"+this.name+", dept loc"+this.loc; }}
class Emp{ private String name; private int age; private Dept dept; //所属部门 private Emp mgr; //所属领导
public Emp(String name , int age){ this.name = name ; this.age = age; }
public void setDept(Dept dept){ this.dept =dept; } public void setMgr(Emp mgr){ this.mgr = mgr; }
public Dept getDept(){ return this.dept; }
public Emp getMgr(){ return this.mgr; }
public String getInfo(){ return "雇员姓名 :" +this.name+",雇员年龄 :"+this.age; }}public class ArrayDemo{ public static void main(String args []){ Dept dept = new Dept("财务部","合肥"); Emp empA = new Emp("菜菜",18); Emp empB = new Emp("学学",18); Emp empC = new Emp("瑞瑞",18); empA.setDept(dept); empB.setDept(dept); empC.setDept(dept); empA.setMgr(empB); empB.setMgr(empC); dept.setEmps(new Emp []{empA,empB,empC});
System.out.println(dept.getInfo()); for(int x = 0 ; x < dept.getEmps().length; x++){ System.out.println("\t|-"+dept.getEmps()[x].getInfo()); if(dept.getEmps()[x].getMgr()!= null) System.out.println("\t\t|-"+dept.getEmps()[x].getMgr().getInfo()); } }}子类覆写
class Person{ private String name; private int age; public Person(String name , int age){ this.name = name; this.age = age; } @Override public String toString(){ return "name:"+this.name+"age:"+this.age; }}
public class duotai{ public static void main(String args []){6 collapsed lines
Person per = new Person("dog", 18); System.out.println(per); System.out.println(per.toString());
}}