过关全靠idea
掌握知识点
- 类的对象类型转换
- 类的继承和多态
- 向上转型
- 向下转型
- instanceof 方法
通关源码(1)
/**
* Create By 刘鸿涛
* 2021/12/13 18:01
*/
class Animal{
// 定义动物类的属性
public String name = "动物";
public static String staticName = "可爱的动物";
// 定义动物类的行为方法
public void eat() {
System.out.println("动物吃饭");
}
public static void staticEat() {
System.out.println("可爱的动物正在在吃饭");
}
}
// 定义猫类,该类继承动物类
public class Cat extends Animal{
// 定义猫类的属性
public String name = "猫";
public String str = "可爱的小猫";
public static String staticName = "我是喵星人";
// 定义猫类的行为方法
public void eat() {
System.out.println("猫吃饭");
}
public static void staticEat() {
System.out.println("喵星人在吃饭");
}
public void eatMethod() {
System.out.println("猫喜欢吃鱼");
}
public static void main(String[] args) {
// 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
/********* Begin *********/
// 向上转型,把猫类对象赋值给动物类
Animal cat = new Cat(); //父类类型 引用名 = new 子类类型();
// 向下转型,将动物类引用转换为猫类对象
Cat cat1 = (Cat)cat; //子类类型 引用名 = (子类类型)父类引用;
// 输出Animal类的name变量
System.out.println(cat.name);
// 输出Animal类的staticName变量
System.out.println(cat.staticName);
// 输出Cat类的eat()方法
cat.eat();
// 输出Animal类的staticEat()方法
cat.staticEat();
// 调用Cat类的str变量
System.out.println(cat1.str);
// 调用Cat类的eatMethod()方法
// ((Cat) cat).eatMethod(); //同cat1.eatMethod();
cat1.eatMethod();
/********** End **********/
}
}
通关源码(2)
/**
* Create By 刘鸿涛
* 2021/12/13 20:38
*/
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;
}
}
public class Tests {
public static void main(String args[]) {
Fruits f = new Fruits("水果");
Apple a = new Apple("苹果","red");
Pear p = new Pear(";梨","yellow");
// 请在下面的Begin-End之间按照注释中给出的提示编写正确的代码
/********* Begin *********/
// 依次判断 f、a、p是否为 Fruits的子类对象
boolean a1 = f instanceof Fruits;
boolean a2 = a instanceof Fruits;
boolean a3 = p instanceof Fruits;
System.out.println(a1 + "\n" + a2 + "\n" + a3);
// 把梨类对象赋值给水果类,其中name值为bigPear,颜色为green
f = new Pear("bigPear","green"); //
// 输出当前水果类引用的名称
System.out.println(f.name);
// 依次判断当前水果类引用是否为水果类和梨类的子类
System.out.println(f instanceof Fruits);
System.out.println(f instanceof Pear);
// 将当前水果类引用强转为梨类
Pear p1 = (Pear) f;
// 输出当前梨类的颜色
System.out.println(p1.pcolor);
/********** End **********/
}
}