Java(1)在main方法里新建一个Dog类的上转型对象d2(new调用构造方法, Animal d2 = new ….),然后打印输出的d2的run和eat方法,观察java的多态 (2)将d2 强制转换为Dog类型,并使用关键字instanceof判断d2是否是Dog类型,如果是打印输出d2的种类值。
时间: 2023-12-06 20:45:31 浏览: 105
Java对象类型的判断详解
1. 代码如下:
```java
public class Main {
public static void main(String[] args) {
Animal d2 = new Dog();
d2.run();
d2.eat();
}
}
class Animal {
public void run() {
System.out.println("Animal is running.");
}
public void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
public void run() {
System.out.println("Dog is running.");
}
public void eat() {
System.out.println("Dog is eating.");
}
}
```
输出结果为:
```
Dog is running.
Dog is eating.
```
这是因为我们创建了一个Animal类型的引用d2,但实际上它指向的是Dog类型的对象。当我们调用d2的run()和eat()方法时,实际上是调用了Dog类中重写的方法。
2. 我们可以使用instanceof关键字来判断d2是否是Dog类型,代码如下:
```java
if (d2 instanceof Dog) {
System.out.println("d2 is a Dog.");
}
```
完整代码如下:
```java
public class Main {
public static void main(String[] args) {
Animal d2 = new Dog();
d2.run();
d2.eat();
if (d2 instanceof Dog) {
System.out.println("d2 is a Dog.");
Dog dog = (Dog) d2;
dog.bark();
}
}
}
class Animal {
public void run() {
System.out.println("Animal is running.");
}
public void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
public void run() {
System.out.println("Dog is running.");
}
public void eat() {
System.out.println("Dog is eating.");
}
public void bark() {
System.out.println("Dog is barking.");
}
}
```
输出结果为:
```
Dog is running.
Dog is eating.
d2 is a Dog.
Dog is barking.
```
在代码中,我们首先使用instanceof关键字判断d2是否是Dog类型,如果是则将其强制转换为Dog类型,并调用Dog类中的bark()方法。注意,强制转换的过程中,如果d2不是Dog类型,将会抛出ClassCastException异常。因此,在进行强制转换之前,最好先使用instanceof进行类型判断。
阅读全文