-4
interface Drivable{}
class Vehicle implements Drivable{}
class Car extends Vehicle{}

Vehicle x= new Vehicle();
Drivable x= new Vehicle();
Car x = new Vehicle();
Object x = new Vehicle();
Vehicle[] x = new Vehicle();

how many of those are right? I am confused that if the second one Drivable=... and 4th Object x=.. are right

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
Z Cherry
  • 13
  • 1

3 Answers3

0

Car x = new Vehicle(); is wrong, and Vehicle[] x = new Vehicle(); is wrong.

The 2nd statement is good - no problem with having an iterface declared which points to a concrete implementation of the interface. Best practice actually (abstraction and hiding the implementation).

The 3rd statement is illegal - you cannot declare a concrete implementation which will reference the base class. Why ? you will be missing expected behaviors of the declared type....

The 4th statement is good, similiar to the 2nd statement only with using a base implementing class instead of an interface.

The 5th statement is wrong but easy to fix : Vehicle[] x = {new Vehicle()};

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
0

All of your classes are of type "Drivable"

"Vechile" is of type "Drivable", "Car" is of type "Vehicle", therefore a "Car" is a "Vehicle".

Both a "Car" and a "Vehicle" are "Drivable".

All of your initializations are correct, except the "Car x = new Vehicle();" and the array initialization, which should look like this

Vehicle[] x = new Vehicle[] { 
    //Vehicles go here
};
Joe
  • 1,316
  • 9
  • 17
0

This is wrong, because every car is vehicle but not the other way i.e. every vehicle may not be a car. Inheritance is "type of" i.e. car is type of vehicle.

Car x = new Vehicle();

Here the x is of array type, so the initialization is wrong.

Vehicle[] x = new Vehicle();

It should be

Vehicle[] x = new Vehicle[size];