1.Explain the concepts of Encapsulation, Inheritance and Polymorphism. In the context of an example explain the benefits of the above mentioned concepts. Note that you do not have to write any code.
Encapsulation: objects have attributes and methods combined into one unit. Instead of accessing values directly, encapsulation protects the values of the variables by only allowing values to change using method calls.
Inheritance:one class takes on characteristics of another class and extends it. the parent class acts like a template to the child class. the child class can access any methods and variables and can also define its own variables and methods. this helps in making the design a simpler process as you keep reusing the code.
Polymorphism:means the object can have multiple forms. different classes can have the same method name but they have different parameters.That methods behaviour will differ depending on the object type it is dealing with.
2.Create an inheritance hierarchy of Vehicle: Bicycle, Car, and Truck. In the base class (Vehicle class), provide one method that are common to all Vehicle classes (say, getNoOfWheels method – assume that Trucks have more than 6 wheels), and override this in the derived classes to return different number of wheels based on the specific type of Vehicle. In the main() method of a class named Assignment2, create an array of Vehicle, fill it with different specific types of Vehicles, and call your base-class methods to see what happens.
public class Vehicle ( ) {
public int getNoOfWheels ( ) {
return 0;
}
}
public class Bicycle extends Vehicle ( ) {
public int getNoOfWheels ( ) {
return 2;
}
}
public class Car extends Vehicle ( ) {
public int getNoOfWheels ( ) {
return 4;
}
}
public class Truck extends Vehicle ( ) {
public int getNoOfWheels ( );
return 12;
}
}
public class Assignment2 ( ) {
public static void main (String [ ] args) {
Vehicle veh [ ] = new Vehicle [3];
Bicycle bike = new Bicycle ( );
Car car = new Car ( );
Truck tr = new Truck ( );
veh[0] = bike;
veh[1] = car;
veh[2] = tr;
for (int i = 0; i <>
System.out.println (veh[i].getNoOfWheels( ));
}
}
No comments:
Post a Comment