Let's delve into the distinction between Java variables that hold subclass objects and those that hold parent class objects using a concrete example.

Imagine we have a class hierarchy like this:javaclass Animal { // Animal class code}

class Dog extends Animal { // Dog class code}

Now, let's create a Dog object and assign it to two different variables:javaDog myDog = new Dog();Animal myAnimal = myDog;

Here, myDog is a Dog type variable, while myAnimal is an Animal type variable.

The primary difference lies in their usage. Since myDog is of type Dog, it can access Dog class-specific methods and fields. For instance, if Dog has a bark() method, we could invoke it using myDog.bark().

Conversely, myAnimal, being an Animal type, can only access methods and fields defined in the Animal class. We cannot call myAnimal.bark() because bark() is not part of the Animal class.

However, because myAnimal is an Animal type, we can assign any object that is an instance of Animal (or its subclasses) to it. This means we can assign a Cat object to myAnimal:javaCat myCat = new Cat();myAnimal = myCat;

In essence, the main difference is that a parent class variable can only access parent class methods and fields, while a subclass variable can access both parent and subclass-specific methods and fields. Nevertheless, the parent class variable's ability to hold any object of its type or its subclasses grants it greater flexibility in assigning and utilizing objects.

Java Subclass vs Parent Class Variable: Understanding the Differences with Example

原文地址: https://www.cveoy.top/t/topic/mZAh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录