1.What are the benefits of inheritance?
a) you can reuse blocks of code,because the child class has access to the parent's fields and methods.
b) Parent constructors can be invoked from the child, and their private fields can be accessed using the superclass' public accessing methods.
c) The child class can declare fields and methods that are not in the parent.
d) Method over-riding can be used (the child method can over-ride the parent method).
e) Inheritance can also make application code more flexible to change because classes that inherit from a common superclass can be used interchangeably. If the return type of a method is superclass Example, then the application can be adapted to return any class that is descended from Examplethe benefits of inheritance is that you can reuse the code and maintainability (only need to change code in the parent, and it is reflected in the child class).
Explain each benefit in the context of an example.
class Animal {
String name;
double age;
double height;
Account() {
}
Account(String n, double b, double d) {
name = n;
age = b;
height = d;
}
void getAge() { **a
System.out.println("Age is : " +age);
}
}
public class Farm extends Animal{
double cattle; **c
Farm() {
}
Farm(String n, double b, double d, double o) {
super(n, b, d); **b
cattle = o;
}
public static void main(String args[]) {
Farm frm = new Farm(“cow”, 20, 5.5, 1000);
System.out.println(frm.Age()); **a
System.out.println("This animal is " + frm.name);
System.out.println (getAge());
}
void getAge() { **d
System.out.println("The age is" + cattle); }
}
2. Does Java support multiple inheritance? Justify your answer.
no it is not possible to do that. but with the use of interfaces and inheritance hierarchy (each subclass is linked to a superclass, which ultimately ends with Object at the root) multiple inheritance can be simulated.
3. It is recommended that you should “program to an interface". An example of programming to an interface is given below where an object of type ArrayList is assigned to a List interface reference. Explain the advantage of this approach.
List studentList = new ArrayList();
instead of tying relationships to classes, you can tie them to interfaces as this has the advantage of being able to change the implementation of a program, with minimal effort.
No comments:
Post a Comment