package dbr2020075090;

public class Fruits {
	/**
	 * 判断梨类、苹果类和水果类的关系,并通过对象类型转换调用彼此的属性和方法。
	 */
	 
	    public String name; // 定义水果名称
	    Fruits (String name) {
	        this.name = name;
	    }
	}
	 
	// 苹果类继承水果类
	class Apple extends Fruits {
	   
	    public String acolor; // 苹果颜色
	 
	    public Apple(String name, String acolor) {
	        super(name);
	        this.acolor = acolor;
	    }
	}
	// 梨类继承水果类
	class Pear extends Fruits {
	    public String pcolor; // 梨的颜色
	 
	    public Pear(String name, String pcolor) {
	        super(name);
	        this.pcolor = pcolor;
	    }
	}

package dbr2020075090;

public class Tests {

	    public static void main(String args[]) {
	        Fruits fruits = new Pear("Pear:","yellow");
	        Fruits fruit = new Apple("Apple:","red");
	        // 输出当前水果类引用的名称
	        System.out.println(fruits.name);
	        Pear pear = (Pear) fruits;
	        System.out.println(pear.pcolor);
	        System.out.println(fruit.name);
	        Apple apple = (Apple) fruit;
	        System.out.println(apple.acolor);
	    }
	}

posted on 2022-05-11 17:04  羲和i  阅读(55)  评论(0)    收藏  举报