gpt4 book ai didi

java - 请解释一下这种情况下的Java继承

转载 作者:行者123 更新时间:2023-12-02 09:22:24 26 4
gpt4 key购买 nike

我正在学习Java,无法理解继承的一些技巧。示例:

  • 我们有一个类Animal
  • 我们有一个类Cat,扩展了Animal
  • 我们有一个类Tiger,扩展了Cat

问题:

1)为什么Cat使用Tigers方法?请参阅下面的“make_a_sound”方法示例。它来自 Tiger,但 Cat 可以使用它。

2)为什么Cat看不到Tiger的任何属性?Cat可以使用Tiger的“make_a_sound”方法,但看不到它的属性......很奇怪。

谢谢,根纳季

public class Solution {
public static void main(string[] args) {

Cat cat = new Tiger();

// The result is from Tiger class: A tiger says RRRRR & new tiger property
// Why???
cat.make_a_sound();

// Only cat's and Animal's properties are visible. No Tiger's properties
System.out.println(cat.this_is_a_cat);
}

// Base class
public class Animal {
public String this_is_an_animal = "Animal";

public void make_a_sound() {
System.out.Printf("I'm an animal");
}
}

// Extends base class
public class Cat extends Animal {
public String this_is_a_Cat = "Hi, I'm a cat";

public void make_a_sound() {
System.out.Printf("A cat says meey");
}
}

// Extends prev. class
public class Tiger extends Cat {
public String this_is_a_Tiger = "Tiger";

public void make_a_sound() {
System.out.Println("A tiger says RRRRRR");

this_is_a_Tiger = "new tiger property";
System.out.println(new_tiger_property);
}
}
}

最佳答案

您将 cat 定义为 Cat 类型。这意味着 cat 可以做任何其他 Cat 可以做的事情。 Animal 对象确实定义了 make_a_sound 函数,因此它可用于所有 Animal 实例。当您运行代码时,变量 cat 指向一个 Tiger 实例,因此当调用 make_a_sound 时,它就是 Tiger< 中的实例 运行。这就是继承的全部意义。

对于你的第二个问题,catCat 类型,因此你只能用它做任何 Cat 对象可以做的事情。由于 this_is_a_Tiger 不是每个 Cat 对象都具有的东西,因此它对 cat 不可用,即使 cat 确实指向一只老虎

但是你可以这样做:

if (cat instanceof Tiger) {
Tiger tiger = (Tiger)cat;
System.out.println(tiger.this_is_a_Tiger);
}

关于java - 请解释一下这种情况下的Java继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58602061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com