So say I have a class Vehicle and subclass car that have instantiated objects in the main (Java)
Vehicle v = new Vehicle();
Car c = new Car();
When we do...
Vehicle c1 = new Car();
What does the word vehicle represent and what does the word car represent in this casting?
(I was basically asked in an interview what "type" c1 is and I couldn't figure out if c1 is type vehicle with a car implementation or type Car that can only use Vehicle's methods)
CodePudding user response:
c1 is a variable that can hold a reference to any Vehicle.
The object it refers to is a Car, which is a Vehicle;
Consider this:
Vehicle c1 = new Car();
c1 = new Bus(); // we suppose Bus also subclasses Vehicle
The variable c1 does not magically change its type. The two objects it refers to in sequence have (unmagically) different types.
The important thing in this to my way of thinking is to understand the difference between object and variable.
CodePudding user response:
// create a reference of type Vehicle
// References are stored in the Stack (name c1, value null)
Vehicle c1;
// create an object (instance) in the heap of type Car
// hold the address of this object into the c1 reference
c1 = new Car() ;
What is an Object? An object is a real-world or software entry which has attributes(instance fields) and behavior(instance methods). The object is created with a new operator in the heap. e.g. new ClassName(); . Objects are instantiated when class is loaded into memory. Objects are also called as Instances.
What is a Reference? Reference holds the address of an object or instance. Whenever we want to call instance methods, we use this reference which holds the address of the object. References are like C pointers.
More information here https://levelup.gitconnected.com/what-is-difference-between-reference-object-instance-and-class-24721e526f9b