Inheritance
- Does Java support multiple level inheritance?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
Java supports multiple level inheritance through implementing multiple interfaces.
- What is the outcome of below Square_Shape_Example class?
class Shape
{
public int area()
{
return 1;
}
}
class Square extends Shape
{
public int area()
{
return 5;
}
}
public class Square_Shape_Example
{
public static void main(String[] args)
{
Shape obj = new Shape();
Square square = new Square();
obj = square;
System.out.println(obj.area());
}
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: E
Child object can be assigned to parent variable without change in behaviour.
- What is the outcome of below code Rectangle_Example class?
class Shape
{
public int area()
{
return 2;
}
}
class Rectangle extends Shape
{
public int area()
{
return 6;
}
}
public class Rectangle_Example
{
public static void main(String[] args)
{
Shape obj = new Shape();
Rectangle obj0 = new Rectangle();
obj = obj0;
System.out.println(obj.area());
}
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
Child object can be assigned to parent variable without change in behaviour.
- What is the outcome of below code SquareExample class?
class Shape
{
public int area()
{
return 2;
}
}
class Square extends Shape
{
public int area()
{
return 7;
}
}
public class SquareExample
{
public static void main(String[] args)
{
Shape obj = new Shape();
Square obj0 = new Square();
obj0 = obj;
System.out.println(obj0.area());
}
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
Compilation Error
SquareExample.java:23: error: incompatible types: Shape cannot be converted to Square
obj0 = obj;
^
1 error
- What is the outcome of below code Output class?
class Shape
{
public int area()
{
return 2;
}
}
class Square extends Shape
{
public int area()
{
return 5;
}
}
class Rectangle extends Shape
{
public int area()
{
return 7;
}
}
public class Output
{
public static void main(String[] args)
{
Shape obj = new Shape();
Square obj0 = new Square();
Rectangle obj1 = new Rectangle();
obj1 = (Rectangle)obj;
System.out.println(obj0.area());
}
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
ClassCastException is thrown as we cannot assign parent object to child variable.
Exception in thread "main" java.lang.ClassCastException: Shape cannot be cast to Rectangle
at Output.main(Output.java:32)