面向对象,封装,多态

这是一个面向对象的小案例,自我感觉良好若有错误请大佬支指出
/*
 * 定义一个人
 * 这个人有名字,有爱人(lover)
 * 我们还能查询这个人婚姻情况(getMarried())
 * 这个人还有个结婚的方法 Married()
 * 这个人还能离婚OutMarry()
 */
public class Person {
  private String name;
  private Person lover;
  //默认人没有名字
  public Person(){
 this("没有名");
 
  }
  //对名字这个变量进行封装
  public Person(String name){
 this.name=name;
 
  }
  //结婚方法,传递参数(Person引用类型)
  public Person Married(Person lover){
 this.lover=lover;
 lover.lover=this;
 //当前爱人的爱人就是自己(this)
 return this;
  }
  //查询婚姻情况
  public void getMarried(){
       if(this.lover==null){
      System.out.println(this.name+"还没有结婚");
       }
       else{
      System.out.println(this.lover.name+"和"+this.name+"结婚了");
       }


  }
  //离婚,并传递被离婚的对象
  public Person OutMarry(Person lover){
 this.lover=null;
 //离婚就是当前爱人变为空
 lover.lover=null;
 //被离婚的爱人也设为空(此举是为了避免a把b离婚了,当查询b的婚姻情况时b没有离婚的可能)
 System.out.println(this.name+"离婚了");
 return this;

 
  }
  

}

测试类

public class PersonDemo {
   public static void main(String[] args){
  Person a =new Person("张三");
  Person b =new Person("李四");
  a.Married(b);
  //a和b结婚
  a.getMarried();
  //查询a的婚姻情况
  b.OutMarry(a);
  //b把a离婚
  a.getMarried();
  //查询a的婚姻情况
  
  
   }
}

猜你喜欢

转载自blog.csdn.net/fyangfei/article/details/78586081