What Is Not Possible Using Inheritance In Java

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.

2. Members that have default accessibility in the super-class are also not inherited by sub-classes in other   packages, as these members are only accessible by their simple names in sub-classes within the same     package as the super-class.

3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.

4. A subclass can extend only one superclass

 

class Vehicle {

 

// Instance fields

int noOfTyres;         // no of tyres

private boolean accessories;            // check if accessorees present or not

protected String brand;                   // Brand of the car

// Static fields

private static int counter;                 // No of Vehicle objects created

// Constructor

Vehicle() {

System.out.println(“Constructor of the Super class called”);

noOfTyres = 5;

accessories = true;

brand = “X”;

counter++;

}

                                                       // Instance methods

public void switchOn() {

accessories = true;

}

public void switchOff() {

accessories = false;

}

public boolean isPresent() {

return accessories;

}

private void getBrand() {

System.out.println(“Vehicle Brand: ” + brand);

}

                                                                // Static methods

public static void getNoOfVehicles() {

System.out.println(“Number of Vehicles: ” + counter);

}

}

class Car extends Vehicle

{

private int carNo = 10;

public void printCarInfo() {

System.out.println(“Car number: ” + carNo);

System.out.println(“No of Tyres: ” + noOfTyres);                         // Inherited.

//  System.out.println(“accessories: ”    + accessories);                  // Not Inherited.

System.out.println(“accessories: ” + isPresent());                          // Inherited.

//        System.out.println(“Brand: ”     + getBrand());                    // Not Inherited.

System.out.println(“Brand: ” + brand);                                         // Inherited.

//  System.out.println(“Counter: ”    + counter);                           // Not Inherited.

getNoOfVehicles(); // Inherited.

}

public class VehicleDetails

{                      // (3)

public static void main(String[] args) {

new Car().printCarInfo();

}

}

 

Output

Constructor of the Super class called

Car number: 10

No of Tyres: 5

accessories: true

Brand: X

Number of Vehicles: 1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s