Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Is the following code valid? Explain


Download 1.52 Mb.
Pdf ko'rish
bet38/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   34   35   36   37   38   39   40   41   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Is the following code valid? Explain.
public class Shape {


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.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   34   35   36   37   38   39   40   41   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling