Overriding And Overloading - Study Mode

[#46] Determine output: class A{
public void printValue(){
System.out.println("Value-A")
}
}
class B extends A{
public void printNameB(){
System.out.println("Name-B")
}
}
class C extends A{
public void printNameC(){
System.out.println("Name-C")
}
}
public class Test{
public static void main (String[] args){
B b = new B()
C c = new C()
newPrint(b)
newPrint(c)
}
public static void newPrint(A a){
a.printValue()
}
}
Correct Answer

(B) Value-A Value-A

Explanation

Solution: Class B extended Class A therefore all methods of Class A will be available to class B except private methods. Class C extended Class A therefore all methods of Class A will be available to class C except private methods.

[#47] What is the output for the below code? class A{
private void printName(){
System.out.println("Value-A")
}
}
class B extends A{
public void printName(){
System.out.println("Name-B")
}
}
public class Test{
public static void main (String[] args){
B b = new B()
b.printName()
}
}
Correct Answer

(B) Name-B

Explanation

Solution: You can not override private method , private method is not availabe in subclass . In this case printName() method a class A is not overriding by printName() method of class B. printName() method of class B different method. So you can call printName() method of class B.

[#48] What is the output for the below code? class A{
public A(){
System.out.println("A")
}
public A(int i){
this()
System.out.println(i)
}
}
class B extends A{
public B(){
System.out.println("B")
}
public B(int i){
this()
System.out.println(i+3)
}
}
public class Test{
public static void main (String[] args){
new B(5)
}
}
Correct Answer

(A) A B 8

Explanation

Solution: Constructor of class B call their super class constructor of class A (public A()) , which execute first, and that constructors can be overloaded. Then come to constructor of class B (public B (int i)).

[#49] What will be the output of the following Java program? final class A
{
int i
}
class B extends A
{
int j
System.out.println(j + " " + i)
}
class inheritance
{
public static void main(String args[])
{
B obj = new B()
obj.display()
}
}
Correct Answer

(D) Compilation Error

[#50] What will be the output of the following Java program? class Alligator
{
public static void main(String[] args)
{
int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}}
int [][]y = x
System.out.println(y[2][1])
}
}
Correct Answer

(C) 7