Top 50 Java OOPs Interview Questions

The blog provides the common asked interview questions on OOPS concepts in java, interview questions on abstract class, interview questions on constructor, interview questions on constructor chaining, interview questions on method overloading , interview questions on method overriding, java abstraction interview questions , java encapsulation interview questions, java inheritance interview questions, java polymorphism interview questions, marker interface questions, copy constructor questions in java, Association vs composition questions, Inheritance vs Polymorphism questions and many more

Java OOPs Interview Questions could be helpful for both freshers and experienced professionals

conjunctionally What is OOPS Concept in Java ? 

OOPS means Object -Oriented Programming System . In OOPS the programs written are considered to be a collection of objects where each object is an instance of the class. 

Sinhyeon What is Class in Java ? 

A class is a blueprint or a representation of the type of Object which includes the class member variables and member functions.  For instance , consider the class classroom which contains chairs and tables.

package core.java.planforexams;

public class Classroom {

	 int chair ;
	 int table ;
	 
	 public Classroom(){
		 chair = 10;
		 table = 4;
	 }
	 
	 public int getChairCount() {
	   System.out.println(" Total Chairs available..." + chair);
		 return chair;
		 
	 }
	 
	 public int getTableCount() {
		 System.out.println(" Total Table available..." + table);
		 return table;
	 }
	
	public static void main(String[] args) {
		Classroom room = new Classroom();
		room.getChairCount();
		room.getTableCount();
	}
}

What is a Constructor in java ?

A Constructor has the same name as the Class Name as it used for initialization the state of an Object. A Constructor is called at the time of Class Object Creation when new operator is used . If the class does not contain the constructor , then Java Compiler calls the default constructor for the class.

A Constructor does not have the return type.

A constructor in java cannot be abstract, static, final, and synchronized

For instance , the above Classroom example provides the usage of Constructor Classroom which initializes the value for table and chair.

What are the types of Constructor in java ?

The Constructor can be classified as:

Default Constructor: A default constructor is used to initialize the instance variable with default values. A default constructor does not support any value / parameter. If the class does not have a constructor , then the java compiler invokes the default constructor.

Parameterized Constructor: The parameterized constructor is initialize the instance variable with the values accepted as parameters.

Does Constructor return any value ?

Yes, the constructor implicitly returns the current instance of the class

Does java supports overloading the constructors ?

Yes. Constructors can be overloaded in java . The class could have multiple constructor with different arguments passed to the constructor. The constructor with parameters is also called as Parameterized Constructors.

package core.java.planforexams.oops;

public class ConstructorOverload {

	
	public ConstructorOverload(String OneParameter) {
		System.out.println(OneParameter);
	}
	public ConstructorOverload(String OneParameter, String TwoParameter) {
		System.out.println(OneParameter + "  " +TwoParameter );
	}
	public static void main(String[] args) {
		ConstructorOverload obj = new ConstructorOverload("Single Parameter");
		ConstructorOverload obj2 = new ConstructorOverload("First Parameter", "Second Parameter");

	}

}

Is it possible to inherit the constructor in java ?

No. Constructor in java cannot be inherited

Is it possible to declare constructor as final in java ?

No. Constructor in java cannot be declared as final

What is Copy Constructor in java ?

Java does not support copy constructor like C++ but it allows to copy the values from one object to another object. The possible ways to copy the object values are given below

  • Copy object values by Constructor
  • Copy object values by assigning to another object
  • Copy object values by invoking the clone() method of class java.lang.Object

Difference between a Java Constructor and a Java Method ?

Java Constructor java method
 A constructor in java is used to initialize the state of an object A method in java is used to depict the behavior of an object
 A constructor does not have a return type A method must have a return type like void, int , string
 A constructor is invoked implicitly  A method is invoked explicitly
 Default constructor is invoked by the java compiler if class does not contain a constructor  No default method is invoked by the java compiler
 A Constructor name must be same as class name A method could have any name

What is Encapsulation in java ? 

Encapsulation is the process which helps in hiding the sensitive data from the users. For instance, the below class includes member variables and member functions where the member variable personName and age are declared as private which restricts the outside world to class member variable.  

package core.java.planforexams.oops;

public class Person {
	 private String personName;
	 private int age;

	 public String getPersonName() {
		return personName;
	}

	public void setPersonName(String personName) {
		this.personName = personName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	 
	public static void main(String[] args) {
		Person obj = new Person();
		obj.setPersonName("Mohit Sharma");
		obj.setAge(28);
		
		System.out.println(" Name is :::" + obj.getPersonName() + " " + "Age is :::" + obj.getAge());

	}

}

What is inheritance in Java ? 

Inheritance is the process in which one class inherits the attributes of another class. Inheritance can be classified as given below:

Base Class / Super Class: The class from which attributes are inherited

Derived Class / Sub Class: The class which inherits the attribute from base / super class

To inherit the attributes from base class, derived class uses the “extends” keyword

The base class with “final” keyword cannot be extended.

The inheritance concept is also known as IS-A relationship as derived class extends base class and thus creates a relationship with each other.

package core.java.planforexams.oops;

public class Tutorials {
	void  getProvider() {
		System.out.println (" planforexams.com");
	}
	
	void  getTutorials() {
		System.out.println (" Online Tutorials for C++ , PHP, Python");
	}
}

package core.java.planforexams.oops;

public class AddCourses extends Tutorials{

	 void addNewCourse() {
		 System.out.println("New Java Course Added");
	 }
	public static void main(String[] args) {
		AddCourses course = new AddCourses();
		course.getProvider();  // Method defined in Base Class 
		course.getTutorials();  // Method defined in Base Class
		course.addNewCourse(); // // Method defined in Derived Class
		}

}

What is Abstraction in Java ? 

Abstraction is the process through which only the relevant data is being shown and hides the implementation details behind the data processing. For instance, when the user logs into Facebook, twitter with the credentials the application shows the data related to your posts and likes but hides the complexity of data processing.

Abstraction can be achieved in 2 ways:

Using Abstract Class: The abstract class could have concrete methods and thus provides partial abstraction

Using Interfaces: An interface has all abstract methods and thus provides 100% abstraction

package core.java.planforexams.oops;

abstract class  AbstractExample {

	abstract void MethodOne();
	
	abstract void MethodOTwo();

	   //This is concrete method with body
	   void MethodThree(){
	      System.out.println (" This is a concrete method in anstract class.. ");
	   }
}

What are the types of Inheritance supported by Java ?

The inheritance in java could be of 3 types:

Single Inheritance : Single Inheritance is where the single Derived Class (B) inherits the Base Class (A) .

Multi Level Inheritance: Multi level Inheritance is where the Base Class (A) is inherited by Derived Class (B) and Derived Class (B) is inherited by Derived Class (C) .

Multiple Inheritance: Multiple inheritance is where derived class extends more than one class. Multiple inheritance is not supported in java to avoid ambiguity but allows to implement multiple interfaces .

Hierarchical Inheritance: Hierarchical Inheritance is where the Base Class (A) is inherited by Derived Class (B) and Derived Class (C)

Hybrid Inheritance: A hybrid inheritance is a combination of multiple inheritance and multi level inheritance.

What are wrapper classes in java ?

The wrappers classes converts the primitive types to objects and objects to primitive types. J2SE5.0 onwards , new feature of autoboxing converts primitive types to objects automatically and unboxing converts objects to primitive types 

Primitive Types Wrapper Classes
booleanBoolean
charCharacter
byte Byte
short Short
intInteger
longLong
floatFloat
doubleDouble

Difference between Abstract Class and a Interface in Java ? 

Difference between Abstract Class and Interface in Java

Does Java support operator overloading ?

No. Java does not support Operator overloading

Does Java support Multiple Inheritance ?

No, java does not support multiple inheritance to avoid ambiguity. For instance , consider the below example

Consider Class ABC with method alphabetCount()

Class LMN and Class PQR extends Class ABC 

Class XYZ extends Class LMN and Class PQR

Now Class LMN and Class PQR have overridden the class ABC method – alphabetCount()

and Class XYZ also wants to override the  method – alphabetCount() but as class LMN and PQR both have the implementation of method alphabetCount() , it leads to ambiguity.  This problem in java is also known as Diamond problem.

Difference between compile time (static binding)  and run time polymorphism (dynamic binding) in java ?

Compile Time polymorphism or Static Binding in Java Run Time polymorphism or Dynamic Binding in Java
The bindings which takes place at the compile time are called Static binding in java The bindings which takes place at run time are called Dynamic binding in java 
Compile-time polymorphism  is also called as Early Binding or Static bindingRun-time polymorphism  is also called as Late Binding or Dynamic binding
The method definition and method call are linked during the compile timeThe method definition and method call are determined at run time
Binding of all the static, private and final methods is done at compile-time. Method overloading is an example of Compile-time polymorphism  Method overriding is an example of Run-time polymorphism where method call is determined at run time.
Program execution is faster as objects are determined at compile time Program execution is slower as objects are determined at run time 
Compile-time polymorphism provides less flexibility
Run-time polymorphism provides more flexibility
Static Binding vs Dynamic Binding

Give an example of run time polymorphism in java ?

The Run Time Polymorphism or dynamic binding  in java is technique in which the method call to the overridden method is determined at run time. The overridden method is call through the reference object of super class. The determination of the method call for the derived class or super class is based on the object being referenced at run time.

Run time polymorphism example in java 

package core.java.planforexams.oops;

public class Cars {
void model(){
System.out.println("executed model() of Cars");
} 
} 
package core.java.planforexams.oops;

class Maruti extends Cars{ 
void model()
{
System.out.println("executed model() of Maruti");
} 
public static void main(String args[]){ 
Cars car = new Maruti(); 
car.model(); 
}
}

Does run time polymorphism supports overriding data members in java ?

No, only method overriding is supported in java . Data Members cannot be overridden. 

What is instance of in java ? 

The instance of in java is also called as type comparison operator as it compares the instance with the type. The return type of instance of in java is either True or False.  If the variable with NULL value is compared for instance of , then it returns False.

instance of example in java 

package core.java.planforexams.oops;
public class InstanceofExp {

public static void main(String args[]){
InstanceofExp ins=new InstanceofExp();
// Returns True for comparing instance of for the class
System.out.println(ins instanceof InstanceofExp);
}

}

Can an Interface implements another Interface in Java ? 

No, An Interface can extends another interface but cannot implement it

What is Marker Interface in Java ?

A marker interface also known as tagging interface is used to tag the metadata / information about the object to indicate JVM to behave specially when any class implement these interfaces . A marker interface does not contains any functions or constants. Java provides built-in Marker interfaces like Serialization, Cloneable and Remote

For Instance , if an object is to be cloned, then Cloneable marker interface informs JVM that the current object is to be cloned but If we try to clone an object that doesn’t implement this interface, the JVM throws a CloneNotSupportedException. 

Similarly, if JVM does not find the Serialization marker interface, then NotSerializableException is thrown when we try to call the ObjectOutputStream.writeObject() method

What are manipulators?

Manipulators are the java functions which can be used in conjunction with the insertion (<<) and extraction (>>) operators on an object. endl and setw are examples of manipulators in java

Difference between “IS-A” relationship and “HAS-A” relationship in java ?

“IS-A” relationship is applicable for inheritance in java. A sub class or derived class object is said to have “IS-A” relationship with the super class or interface. If class A extends B then A “IS-A” B. It is also applicable if class A extends B and class B extends C then A “IS-A” relationship with Class C. The “instanceof” operator in java determines the “IS-A” relationship.

When class A has an entity reference with class B, it is known as Aggregation. Aggregation allows code reusability by delegating the method call. Aggregation provides “HAS-A” relationship. 

Aggregation example in java 

 

class Addition{  
 int addNumbers(int One, int Two){  
  return One + Two;
 }  
}  

class UserInput{  
 Addition obj;//aggregation  
int One =5;
int Two = 7;
    
 int  addNumbers(int One, int Two){  
   obj=new Addition();  
   int sum =obj.addNumbers(radius); 
   return sum;  
 }  

Explain Association in java ? 

Association in java depicts the  relationship between classes where a Class A Object invokes instance of Class B Object to access the member variables and member functions . Composition and Aggregation are the types of Association in java.

An association could be

  • One-To-One
  • One-To-Many
  • Many-To-Many
  • Many-To-One

For instance , a relationship between a Teacher and Student could be One-To-Many where 1 teacher teaches many students. Another example for association could be Company and employee where One Company provides employment to many employees

Explain Composition in java ?

Composition in java is another type of Association which depicts the restricted form of Aggregation where two entities are tightly binded to each other.

  • Composition in java represents part-of relationship
  • Composition in java depicts the dependency among entities
  • When there is a composition between two entities, the composed object cannot exist without the other entity

Difference between Aggregation vs Composition in java ?

 Aggregation in java  Composition in java 
Aggregation depicts the loosely coupled relationship where sub class can exist independently without dependency on parent class Composition depicts the tightly coupled relationship where sub class cannot exist independently and has dependency on parent class
Aggregation supports One-To-One, One-To-Many, Many-To-Many, Many-To-One relationship Composition supports One-To-One relationship
Aggregation relation is “HAS-A” Composition relation is “IS-A”

Provide and example of Strategy Pattern used in java ? 

Strategy Pattern in java is quite useful as it allows to embed new strategy without impacting the change on the current implementation. Collections.sort() is an example of Strategy Pattern which defines the collection of related algorithm like bubble sort, merge sort, quick sort , etc and thus when the objects calls for comparison , they could have different strategy being applied but even though Collections.sort()  applies the sorting on the objects and return the result without changing the sorting algorithm.

Strategy pattern changes the behavior of the class by applying the internal algorithm at runtime based on user input. Due to this , Strategy Pattern is part of behavioral design pattern

Describe Decorator Design Pattern usage in java oops concept? 

The Decorator design Pattern is one of the famous Gang of Four (GOF) structural design pattern. The Decorator design Pattern uses composition to provided new functionality at the run time . The Decorator design Pattern is widely used in JDK in java.io package for classes like BufferedInputStream, LineNumberInputStream

For instance, We have a interface pizza which provides implementation methods based on pizza types.
But Now we need to add prices for each Pizza Type. So we can create a Decrator interface which inherits the Pizza Interface

Create a Decorator Implementation class and it will provided implementation for both Pizza Types and Pizza Prices

Difference between Composition and Inheritance in Java ?

Inheritance in java  composition in java 
Inheritance is the concept of extending class at compile time  Composition allows to define a type which can hold different implementation at run-time.
Inheritance is consider static  Composition is consider dynamic
Using inheritance only one class can be extended  and thus provides limited code reusability Composition allows to extend multiple classes and provides better code reusability feature
inheritance does not allow code reuse from final classes Composition allows code reuse from final classes

Name object oriented design principle from SOLID ?

SOLID stands for
S – Single Responsibility Principle
O – Open closed design principle
L – Liskov substitution principle
I – Interface segregation principle
D – Dependency inversion principle

Can we declare a class final and abstract at the same time ?

No. The final class cannot be extended whereas the abstract class need to be extended for implementation which violates the oops concepts and compiler throws an error for wrong declaration in java 

Difference between Abstraction and Polymorphism in java ?

Abstraction in java  Polymorphism in java 
Abstraction is achieved using abstract class and interfaces Polymorphism is achieved using method overloading and method overriding 
Abstraction is a process for implementing the methods at compile time Method overloading is done at compile time whereas method overriding is achieved at run-time

Does java supports 100% object-oriented programming ?

Java does not support 100% Object oriented programming due to the below given points

  • OOPS in java does not support multiple inheritance
  • Java uses primitive types like int, short, long, char, boolean

How method overriding be prevented without using final modifier in java ?

The method overriding can be prevented by marking the method as private or static and thus cannot be overridden.

Is it possible to make abstract class without an abstract method in java ?

Yes. Java  supports creating abstract class without abstract methods. Define the class with “abstract” keyword and it makes the class definition as abstract

Is it possible to declare a Constructor as static in java ?

Static variables and methods does not require object creation to call whereas a Constructor is initialed when the an object is created and thus not allowed to be static

Does abstract class supports declaring static variables and methods ?

Yes. The abstract class supports the declaration of the static variables as well as static methods. As static context ( static variables and methods) does not require object creation, they can be called directly

 

 

package core.java.planforexams.oops;

abstract class StaticCallinAbstractClass {

   static String xyz ="value for Static Variable XYZ "	;
   static void invokeMewithoutObj() {
	   System.out.println("Static method from abstract call invoked");
   }
	
}

package core.java.planforexams.oops;
public class InvokeStaticMembers extends StaticCallinAbstractClass{

	public static void main(String[] args) {
		System.out.println("XYZ:::"+ StaticCallinAbstractClass.xyz);  
		StaticCallinAbstractClass.invokeMewithoutObj();

	}
}

Explain Constructor Chaining in Java ?

Constructor Chaining in java allows to call a Constructor from another Constructor Object of the class using the current class object. To refer a constructor we can use this keyword as given below in the Student example

 

package core.java.planforexams.oops;
public class StudentConstructorChaining {
  int studentId;
  int studentAge;
  String studentName;
  String studentAddress;
  public StudentConstructorChaining (int studentAge)
  {
    this.studentAge = studentAge;
  }
  public StudentConstructorChaining(int studentId, int studentAge)
  {
    this(studentAge);
    this.studentId = studentId;
  }
  public StudentConstructorChaining(int studentId, int studentAge,
                                    String studentName, String studentAddress)   { 
    this(studentId, studentAge);
    this.studentName = studentName;
    this.studentAddress = studentAddress;
  } 
  public static void main (String args[]) {
    StudentConstructorChaining student =
                  new StudentConstructorChaining(11, 28, "Mohit Sharma", "Chandigarh"); 
    System.out.println("Student Id is :::" + student.studentId +
                        " Student Name is :::" + student.studentName + " Student Age is :" +                                          student.studentAge + " Student Address is ::: " + student.studentAddress); } }

Why multiple inheritance not supported in java ?

// Create Class One with method print()
class One{
  void print()
  { System.out.println("print call from Class One Method");
  }
} // Create Class Two with method print() 
class Two {
  void print()
  { System.out.println("print call from Class Two Method");
  } // Class Three extends Class One , Class Two which both contains the method print()
  class Three extends One,Two{ 
    Public Static void main(String args[]){
      Three obj=new Three(); 
      obj.print(); // Cannot identify which Class Method to be invoked... adds ambiguity
    }
  }

Lets understand with the below given example. The class Three inherits Class One and Class Two. If Class One and Class Two contains the same method print() and that is called from Class Three, then it is not possible to identify which class method is to be invoked as it adds ambiguity. Thus , to reduce complexity and to avoid ambiguity, java compiler gives compile time error when multiple classes are extended

 

Leave a Reply

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

*