对象转型的小例子

来源:互联网 发布:淘宝店铺团队架构 编辑:程序博客网 时间:2024/05/29 02:41

package lin.sxt;


class Dw
{
 private String name;
 public Dw(){}
 public Dw(String name)
 {
  this.name = name;
 }
 public String getName()
 {
  return this.name;
 }
}
class Mao extends Dw
{
 private String color;
 public Mao(){}
 public Mao(String name,String color)
 {
  super(name);
  this.color = color;
 }
 public String getColor()
 {
  return this.color;
 }
 
}
class Gou extends Dw
{
 private String sy;
 public Gou(){}
 public Gou(String name,String sy)
 {
  super(name);
  this.sy = sy;
 }
 public String getSy()
 {
  return this.sy;
 }
}


public class ZXtest {
 public void test(Dw x)
 {
  System.out.println(x.getName());
  if(x instanceof Mao)
  {
   Mao x1=(Mao)x;
   System.out.println(x1.getColor());
  }
  if(x instanceof Gou)
  {
   Gou x2 = (Gou)x;
   System.out.println(x2.getSy());
  }
 }

 public static void main(String[] args) {
  ZXtest t= new ZXtest();
  Dw a=new Dw("aaaa");
  Mao b= new Mao("bbbb","red");
  Gou c=new Gou("ccccc","haoting");
  t.test(a);
  t.test(b);
  t.test(c);
  
  
 }
}