098.
}
public class Circle extends Shape{
}
public class ShapeDrawer {
public void drawShape(Shape shape) {
System.out.println(“Drawing Shape..”);
}
}
public class ShapeDemo {
public static void main(String args[]) {
ShapeDrawer shapeDrawer = new ShapeDrawer();
shapeDrawer.drawShape(new Shape()); //Line 1
shapeDrawer.drawShape(new Circle()); //Line 2
}
}
Answer:
Yes, the above code is valid. This
code defines a base class
called Shape with a sub–class called Circle. There is a
ShapeDrawer class with a method called drawShape. The
drawShape method accepts as parameter a Shape instance.
Line 1 invokes the ShapeDawer.drawShape() method with a
Shape object which is valid. Line 2 invokes the
ShapeDawer.drawShape() method with a Circle object.
Since Circle is a sub–class
of Shape, it is okay to pass a
Circle object to the drawShape method.
In general, you can
pass a sub–class object to a method that
accepts an object of the
super–class type.
Why does Java not support multiple inheritance?
099.
Answer:
Multiple inheritance occurs when a class inherits from two
classes. Java does not support multiple
inheritance as it causes
an ambiguity known as the diamond problem. Consider the
following code snippet:
public class Base1 {
public void myMethod() {
System.out.println(“Base1.myMethod”);
}
}
public class Base2 {
public void myMethod() {
System.out.println(“Base2.myMethod”);
}
}
This code defines 2 classes called Base1 and Base2. Both have
a method called myMethod. Now
consider the following code
snippet:
public class Sub extends Base1, Base2{
}
The class Sub extends both Base1 and Base2. A sub–class
inherits all the members of the base class. Since both have a
method
called myMethod, this results in an ambiguity since it is
unclear which method will be inherited by Sub. So,
Java does not
allow this and the above code results in a compilation error.
Do'stlaringiz bilan baham: