Core Java - OOPs Concepts: Inheritance Interview
Questions
51) What is this keyword in Java?
In Java, this keyword is a reference variable that refers to the current object.
There are various uses of this keyword in Java. It is primarily used within the
instance methods of a class to refer to the object on which the method is
invoked. It can be used to refer to current class properties such as instance
methods, variables, constructors, etc. It can also be passed as an argument to
the methods or constructors. It can also be returned from the method as the
current class instance.
To read more: this keyword in Java
52) What are the uses of this keyword?
There are the following uses of this keyword:
○ It can be used to refer to the current class instance variable.
○ It can be used to invoke the current class method (implicitly).
○ The constructor this() can be used to invoke the current class constructor.
○ It can be passed as an argument in the method call.
○ It can be passed as an argument in the constructor call.
○ It can be used to return the current class instance from the method.
Let's understand through a Java program.
public class Main {
private int x;
public void setX(int x) {
this.x = x; // Using 'this' to refer to the instance variable
}
}
To read more this Keyword in Java
53) Can we assign the reference to this variable?
No, it is not possible to assign a new value to this variable in Java. this
keyword is an implicit reference to the current instance of the class and is
automatically set by the Java runtime system when a method is invoked.
However, if we try to do so, the compiler error will be shown. Consider the
following example.
Example
public class Main
{
public Main()
{
this = null;
System.out.println("Main class constructor called");
}
public static void main (String args[])
{
Main obj = new Main();
}
}
Compile and Run
Output
Main.java:5: error: cannot assign to 'this'
this = null;
^
1 error
54) Can this keyword be used to refer to static members?
Yes, it is possible to use this keyword to refer to static members because it is
just a reference variable that refers to the current class object. However, as we
know, it is unnecessary to access static variables through objects. Therefore,
it is not the best practice to use this to refer to static members. Consider the
following example.
public class Main
{
static int i = 10;
public Main()
{
System.out.println(this.i);
}
public static void main (String args[])
{
Main obj = new Main();
}
}
Output
10
55) How can constructor chaining be done using this
keyword?
Constructor chaining enables us to call one constructor from another
constructor of the class with respect to the current class object. Constructor
chaining in Java can be achieved using the this keyword. Consider the
following example that illustrates how we can use this keyword to achieve
constructor chaining.
public class Employee
{
int id,age;
String name, address;
public Employee (int age)
{
this.age = age;
}
public Employee(int id, int age)
{
this(age);
this.id = id;
}
public Employee(int id, int age, String name, String address)
{
this(id, age);
this.name = name;
this.address = address;
}
public static void main (String args[])
{
Employee emp = new Employee(105, 22, "Peter", "Delhi");
System.out.println("ID: "+emp.id+" Name: "+emp.name+" age:
"+emp.age+" address: "+emp.address);
}
}
Output
ID: 105 Name: Peter age: 22 address: Delhi
To read more: Constructor Chaining in Java
56) What are the advantages of passing this into a method
instead of the current class object itself?
As we know, this refers to the current class object; therefore, it must be similar
to the current class object. However, there can be two main advantages of
passing this into a method instead of the current class object.
○ this is a final variable. Therefore, this cannot be assigned to any new value,
whereas the current class object might not be final and can be changed.
○ this keyword can be used in the synchronized block.
Passing this into a method instead of the current class object itself provides
several advantages:
○ Flexibility
○ Encapsulation
○ Consistency
57) What is the Inheritance?
Inheritance is a mechanism by which one object acquires all the properties
and behavior of another object of another class. It is used for Code Reusability
and Method Overriding. Inheritance is a fundamental concept in
object-oriented programming (OOP) that allows a class (subclass or derived
class) to inherit attributes and behaviors from another class (superclass or
base class). Moreover, we can add new methods and fields in your current
class also. Inheritance represents the IS-A relationship that is also known as a
parent-child relationship.
To read more Inheritance in Java
There are five types of inheritance in Java:
○ Single-level inheritance
○ Multi-level inheritance
○ Multiple Inheritance
○ Hierarchical Inheritance
○ Hybrid Inheritance
Note: Multiple inheritance is not supported in Java through a class.
To read more: Types of Inheritance in Java
58) Why is inheritance used in Java?
Various advantages of using inheritance in Java are given below.
○ Inheritance provides code reusability. Inheritance allows subclasses to inherit
attributes and behaviors from a superclass, promoting code reuse. Common
functionality can be defined in a superclass, and subclasses can extend or
specialize it.
○ Runtime polymorphism cannot be achieved without using inheritance.
○ We can simulate the inheritance of classes with real-time objects, which
makes OOPs more realistic.
○ Inheritance provides data hiding. The base class can hide some data from the
derived class by making it private.
○ Method overriding cannot be achieved without inheritance. Inheritance
facilitates polymorphism, allowing objects of a subclass to be treated as
objects of the superclass. By method overriding, we can give a specific
implementation of some basic method contained by the base class.
To read more: Inheritance in Java
59) Which class is the superclass for all the classes?
In Java, the Object class is the superclass of all other classes. Every class in
Java directly or indirectly extends the Object class. The Object class provides
fundamental methods that are inherited by all classes, such as toString(),
equals().
To read more: Object Class in Java
60) Why is multiple inheritance not supported in Java?
To reduce the complexity and simplify the language, multiple inheritance is not
supported in Java. Consider a scenario where A, B, and C are three classes.
The C class inherits A and B classes. If A and B classes have the same
method and we call it from a child class object, there will be ambiguity in
calling the method of A or B class.
The Diamond Problem occurs when a class inherits from two classes that
have a common ancestor, leading to ambiguity in method resolution.
Since the compile-time errors are better than runtime errors, Java renders a
compile-time error if we inherit 2 classes. So, whether we have the same
method or a different one, there will be a compile-time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class Main extends A,B{//suppose if it were
public Static void main(String args[]){
Main obj=new Main();
obj.msg();//Now which msg() method would be invoked?
}
}
The above program gives a compile-time error.
To read more: Multiple Inheritance in Java
61) What is aggregation?
Aggregation can be defined as the relationship between two classes where
the aggregate class contains a reference to the class it owns.
Aggregation is a type of association in object-oriented programming where
one class contains an object of another class, forming a relationship between
them. It represents a "has-a" relationship, indicating that a class has an entity
as a part of its structure.
For example, the aggregate class Employee, having various fields such as age,
name, and salary, also contains an object of the Address class, having various
fields such as Address-Line 1, City, State, and pin-code.
In other words, we can say that Employee (class) has an object of Address
class. Consider the following example.
Address.java
public class Address {
String city, state, country;
public Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
Employee.java
public class Emp {
int id;
String name;
Address address;
public Emp(int id, String name,Address address) {
this.id = id;
this.name = name;
this.address=address;
}
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}
public static void main(String[] args) {
Address address1 = new Address("gzb", "UP", "India");
Address address2 = new Address("gno", "UP", "India");
Emp e=new Emp(111,"varun",address1);
Emp e2=new Emp(112,"arun",address2);
e.display();
e2.display();
}
}
Output
111 varun
gzb UP India
112 arun
gno UP India
To read more: Aggregation in Java
62) What is composition?
Composition is a stronger form of aggregation in object-oriented
programming. Holding the reference of a class within another class is known
as composition. When an object contains another object, if the contained
object cannot exist without the existence of the container object, then it is
called composition. In other words, we can say that composition is a
particular case of aggregation, which represents a stronger relationship
between two objects. Example: A class contains students. A student cannot
exist without a class. There exists a composition between the class and the
students.
Composition is a way to create more robust and tightly integrated structures
by combining objects to form a larger, more complex system.
To read more: Composition in Java
63) What is the difference between aggregation and
composition?
Aggregation represents a weak relationship, whereas composition represents
a strong relationship. Aggregation represents a "has-a" relationship, where one
class has a reference to another class, but the referenced class can exist
independently. Composition also represents a "has-a" relationship, but it is a
stronger form of association. For example, the bike has an indicator
(aggregation), but the bike has an engine (composition).
To read more: Difference Between Aggregation and Composition in Java
64) Why does Java not support pointers?
Java does not support explicit pointers like those found in languages such as
C or C++, as the pointer is a variable that refers to the memory address. They
are not used in Java because they are unsafe(unsecured) and complex to
understand.
65) What is super in Java?
In Java, super is a keyword that is used to refer to the immediate parent class
object. Whenever you create an instance of the subclass, an instance of the
parent class is created implicitly, which is referred to by the super reference
variable. The super() is called in the class constructor implicitly by the
compiler if there is no super or this.
The super keyword is commonly used in scenarios where a class extends
another class, and there is a need to differentiate between the members of the
subclass and the superclass.
class Animal {
Animal() { System.out.println("An animal is created"); }
}
class Dog extends Animal {
Dog(){
System.out.println(" A dog is created");
}
}
class Main {
public static void main(String args[]) {
Dog d=new Dog();
}
}
Output:
An animal is created
A dog is created
To read more: super Keyword in Java
66) How can constructor chaining be done by using the
super keyword?
Constructor chaining in Java refers to the process of calling one constructor
from another within the same class or in the parent class. The super keyword
is used to invoke the constructor of the parent class.
Example
class Person
{
String name, address;
int age;
public Person(int age, String name, String address)
{
this.age = age;
this.name = name;
this.address = address;
}
}
class Employee extends Person
{
float salary;
public Employee(int age, String name, String address, float salary)
{
super(age,name,address);
this.salary = salary;
}
}
public class Main
{
public static void main (String args[])
{
Employee e = new Employee(22, "Mukesh", "Delhi", 90000);
System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+"
Address: "+e.address);
}
}
Compile and Run
Output
Name: Mukesh Salary: 90000.0 Age: 22 Address: Delhi
67) What are the main uses of the super keyword?
There are the following uses of the super keyword:
○ It is used to refer to the immediate parent class instance variable.
○ It is used to invoke the immediate parent class method.
○ The constructor super() can be used to invoke the immediate parent class
constructor.
To read more: super keyword in Java
68) What are the differences between this and super
keyword?
These are the following differences between this and super keyword:
The super keyword always points to the parent class contexts whereas this
keyword always points to the current instance of the class.
The super keyword is primarily used for initializing the base class variables
within the derived class constructor whereas this keyword primarily used to
differentiate between local and instance variables when passed in the class
constructor.
The super and this must be the first statement inside constructor otherwise
the compiler will throw an error.
To read more: Difference between this and super in Java
69) What is the output of the following Java program?
class Person
{
public Person()
{
System.out.println("Person class constructor called");
}
}
public class Employee extends Person
{
public Employee()
{
System.out.println("Employee class constructor called");
}
public static void main (String args[])
{
Employee e = new Employee();
}
}
Output
Person class constructor called
Employee class constructor called
Explanation
The super() is implicitly invoked by the compiler if no super() or this() is
included explicitly within the derived class constructor. Therefore, in this case,
The Person class constructor is called first and then the Employee class
constructor is called.
70) Can we use this() and super() in a constructor?
No, you cannot use both this() and super() in the same constructor because
this() and super() must be the first statement in the class constructor. Using
both in the same constructor would result in a compilation error.
Example:
public class Main {
Main()
{
super();
this();
System.out.println("Main class object is created");
}
public static void main(String []args){
Main t = new Main();
}
}
Output:
Main.java:5: error: call to this must be first statement in constructor
To read more: Difference Between this and super in Java
71) What is object cloning?
Object cloning in Java refers to the process of creating an exact copy of an
object. The clone() method of the Object class is used to clone an object. The
java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create. If we do not implement Cloneable interface, clone()
method generates CloneNotSupportedException. The clone() method creates
a new object with the same state as the original object.
protected Object clone() throws CloneNotSupportedException
To read more: Object Cloning in Java