OOPs interview questions

In the OOPs concept test, the candidate will be mostly asked questions on Inheritance and polymorphism.

Inheritance and runtime polymorphism – What is the output?

class Super {
	Super() { System.out.println("Super"); }
	void fun() {  System.out.println("FSuper"); }
}

public class Child extends Super {
	Child() { System.out.println("Child"); }
	void fun() { System.out.println("FChild"); }

	public static void main(String[] args) {
		// Question 1
		Super s1 = new Super();
		s1.fun();

		// Question 2
		Super s2 = new Child();
		s2.fun();

		// Question 3
		Child s3 = new Child();
		s3.fun();
		
		// Question 4
		Child s4 = new Super();
		s4.fun();
	}
}

Answers:
Question 1: Super \n FSuper. Super class constructor is called first and then the function of super is called.
Question 2: Super \n Child \n FChild. Child class constructor calls Super class default constructor as it’s the first call and then anything inside Child constructor is called. FChild because object created is of type Child.
Question 3: Super \n Child \n FChild. Child class constructor calls Super class default constructor as it’s the first call and then anything inside Child constructor is called. FChild because object created is of type Child.
Question 4: Compilation Error. Child references cannot hold parent details. Doing Child s4 = new Super(); implies that we call any method inside Child class using s4. Now, if Child declares a fun2() and we can do s4.fun2() but this fun2 is not defined for Super class. Hence, there is a problem with the Child holding reference to Super.

Compile-time polymorphism (Method overloading)

public class Overloading {
	// Question 1:
	public void test(int a) {};
	public void test(Double a) {}
	public void test(int a, Double b) {}
	
	// Question 2:
	public void check(int a) {};
	public int check(int a) {};
	
	// Question 3:
	public void fun(List<Integer> var) { }
	public void fun(List<String> var) { }
}

Answer:
Question 1: Valid cases. Method overloading resolution works on data type and number of arguments and not the return type.
Question 2: Invalid cases because the signature is the same. The return type is not considered in function overloading.
Question 3: Invalid case because we can call this method by new ArrayList() as an argument and the compiler will not know which one to call. Hence, this gives a compile-time error. Method overloading resolution works on data type and number of arguments and not the return type.

(Visited 12 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
5 + 23 =