Java MCQs on Inheritance of Java Programming Language.
1. Which of this keyword must be used to inherit a class? Answer: d 2. A class member declared protected becomes a member of subclass of which type? Answer: b 3. Which of these is correct way of inheriting class A by class B? Answer: c 4. Which two classes use the Shape class correctly? a) B,E Answer: a 5. What will be the output of the following Java program? a) 0 6. What will be the output of the following Java program? a) 2 2 7. What will be the output of the following Java program? a) 1 2
a) super
b) this
c) extent
d) extends
Clarification: None.
a) public member
b) private member
c) protected member
d) static member
Clarification: A class member declared protected becomes a private member of subclass.
a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}
Clarification: None.A. public class Circle implements Shape
{
private int radius;
}
B. public abstract class Circle extends Shape
{
private int radius;
}
C. public class Circle extends Shape
{
private int radius;
public void draw();
}
D. public abstract class Circle implements Shape
{
private int radius;
public void draw();
}
E. public class Circle extends Shape
{
private int radius;
public void draw()
{
/* code here */
}
}
F. public abstract class Circle implements Shape
{
private int radius;
public void draw()
{
/* code here */
}
}
b) A,C
c) C,E
d) T,H
Clarification: If one is extending any class, then they should use extends keyword not implements.
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
b) 1
c) 2
d) Compilation Error
Clarification: Class A & class B both contain display() method, class B inherits class A, when display() method is called by object of class B, display() method of class B is executed rather than that of Class A.
output:
$ javac inheritance_demo.java
$ java inheritance_demo
2
class A
{
int i;
}
class B extends A
{
int j;
void display()
{
super.i = j + 1;
System.out.println(j + " " + i);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
b) 3 3
c) 2 3
d) 3 2
Clarification: None
output:
$ javac inheritance.java
$ java inheritance
2 3
class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
b) 2 1
c) Runtime Error
d) Compilation Error
Clarification: Keyword super is used to call constructor of class A by constructor of class B. Constructor of a initializes i & j to 1 & 2 respectively.
output:
$ javac super_use.java
$ java super_use
1 2