I am confused as to the definitions and the logistics behind the superclass and subclass.
2 Answers
In a word - yes. Since a subclass instance "isA" superclass, you can assign it to such a variable.
Consider the following example - a String
is an Object
, so this assignment would be legal:
Object obj = "abcd"; // this is a string literal

- 297,002
- 52
- 306
- 350
To quickly answer your question: yes, it is possible to assign a subclass almost anywhere the superclass goes.
The reasons for this involve inheritance and object oriented programming. Let me give you an example. Let's think about trains and railway cars that are part of the train.
The superclass is RailwayCar. Every RailwayCar has a weight.
public class RailwayCar {
private int weight;
public RailwayCar() {
}
public RailwayCar(int weight) {
setWeight(weight);
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void arriveAtStation(Station station) {}
public void leaveStation(Station station) {}
}
That is just a basic car. However, there are special cars.
// Engines have power in addition to weight
public class Engine extends RailwayCar {
private int power;
public Engine(int weight, int power) {
super(weight);
setPower(power);
}
public void setPower(int power) {
this.power = power;
}
public int getPower() {
return power;
}
}
There are other types of cars. For example, for example, there could be a PassengerCar where the weight might change at each station as passengers get on and off. There are specific types of cars for specific types of cargo. LogCar would contain long logs.
All of these subclasses of RailwayCar may override the station methods (arriveAtStation() and leaveStation()) to perform specific actions by overriding these methods.
All of these cars could be put into the same list or array. For example, RailwayCar[] cars, or List cars = new ArrayList<>();

- 447
- 1
- 5
- 9