0% found this document useful (0 votes)
4 views

Java OOPs surrounding with answers

The document provides a comprehensive overview of Java Object-Oriented Programming (OOP) concepts, including constructors, encapsulation, abstraction, inheritance, polymorphism, method overloading, method overriding, static and non-static methods, and abstract classes. It includes examples and explanations for each concept, detailing how they are implemented in Java. Additionally, it addresses common interview questions related to these topics, making it a useful resource for Java OOP interviews.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java OOPs surrounding with answers

The document provides a comprehensive overview of Java Object-Oriented Programming (OOP) concepts, including constructors, encapsulation, abstraction, inheritance, polymorphism, method overloading, method overriding, static and non-static methods, and abstract classes. It includes examples and explanations for each concept, detailing how they are implemented in Java. Additionally, it addresses common interview questions related to these topics, making it a useful resource for Java OOP interviews.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Java OOPs interview - surrounding questions

Constructor:
1. How will you call parameter less constructor, write one eg
First we should create object for that class.
Eg :
public class Test{
public Test(){
System.out.println(“Welcome”);
}
}
public class MyClass{
public static void main(String[] args){
Test t = new Test();
}
}

2. How will you call parameterized constructor, write one eg


First we should create object for that class with parameters.
Eg :
public class A{
public A(int i){
System.out.println(“Welcome”);
}
}
public class MyClass{
public static void main(String[] args){
A a = new A(10);
}
}

3. Can we have private constructor


Yes we can have private, public, default and protected constructor.

4. Can I override constructor


No, constructor cannot be overridden
It doesn’t have a return type and also for constructors to be overridden it
should have same parameters but in constructors we cannot have same
parameters.
5. Can I overload constructor
Yes, Constructors can be overloaded because in constructors we use same
constructor name but different parameters.

6. Why we can’t override constructor


We cannot override constructors because it doesn’t have a return type and
also for constructors to be overridden it should have same parameters but in
constructors we cannot have same parameters.

7. How will you call parent class constructor, which doesn’t have parameters
The JVM automatically creates a super call in child class to access parent
class constructor. We can call parent class constructor which doesn’t have
parameters by creating object for the child class.
Eg:
class Program{
public void m1(){
System.out.println(“Programming”);
}
}
class Computer extends Program{
public void m2(){
System.out.println(“Computer”);
}
}
public class MyClass{
public static void main(String[] args){
Computer c = new Computer();
c.m2();
c.m1();
}
}

8. How will you call parent class constructor, which have parameters
We can call parent class constructor which has parameters by using super
call with values in child class and creating object for the child class .
Eg :
class M1{
public M1(int a){
System.out.println(“M1”);
}
}
class M2 extends M1{
public M2(){
super(10);
System.out.println(“M2”);
}
}
public class MyClass{
public static void main(String[] args){
M2 m = new M2();
}
}

9. How will you call same class constructor from other constructor
Constructor chain / constructor execution sequence : it is the ability to
call a constructor in another constructor.
Using this() keyword we can call same class constructor from other constructor
(using super() keyword we can call parent class constructor from child class)
Eg :
class M1{
public M1(int a){
System.out.println(“M1”);
}
}
class M2 extends M1{
public M2(){
super(10); //super() is used to call the constructor of M1
System.out.println(“M2-1”);
}
public M2(char c){
this(); // this() is used to call the same class constructor
System.out.println(“M2-2”);
}
}
public class MyClass{
public static void main(String[] args){
M2 m = new M2(‘*’);
}
}

10. Will it give compile time error if we give return type to constructor
No, because it treats it as a normal method.

11. In the inheritance which class constructor will be executed first


Parent class
12. Is the constructor inherited to the child class?
Constructors are not members, so they are not inherited by childclass but
the constructor of parent class can be invoked from the child class.

13. public class A { private A() {} } . what is the correct way to create object
for this class?
A a = new A();

14.public class A { public A(int i) {} } . Does Compiler supply default


constructor for this class?
No, compiler does not add default constructor for this class.

15.public class A
{
public A(int i) {}
}
public class B extends A
{
public B(int i) {}
}
Will the above code compile successfully?
No because we have to declare super keyword with an integer value in
child class because the constructor of parent class has an integer value.

Encapsulation:
1. Give me one scenario example where you have implemented encapsulation.
Students must tell one project scenario to explain the encapsulation.
public class Doctor{
public String name;
public int exp;
public Doctor(String name, int exp){
this.name = name;
this.exp = exp;
}
public void suggestMedicine(String disease){
//return medicine name based on disease
}
}
Here all the logically related data and functions of doctor is stored in Doctor
class.
2. What is the use of encapsulation?
It is used to bind logically related data and functions in a common related
place.

3. which oops feature do you use to achieve data security [or] data hiding
Encapsulation

4. How will you hide data from the external world using encapsulation? Hint :
Students must talk about bean class.
By using bean class data security can be provided since all the variables
of bean class are private and each variable has a getter and setter method.

5. Which methods are used to achieve encapsulation. Hint : setter() getter()


By declaring all the variables in the class as private and writing public
methods in the class to set and get the values of variables.
Defined by the setter and getter methods.

6. What is bean class


If all the variables of a class are private and each variable has a getter and
setter method, then it is known as bean class.

7. Write setter and getter methods for variable private int sno;
public interface MyInterface{
private int sno;
public void set sno(int sno){
this.sno = sno;
}
public void get sno(){
return this.sno;
}
}

Abstraction:
1. How will you achieve abstraction in java?
Abstraction is achieved by using the abstract keyword for abstract class
and interfaces.

2. Give me one real time example (not java) of abstraction?


ATM
Say for example the user wants to withdraw cash, he just needs to enter the pin,
amount and the otp and he gets the cash but the internal working of the atm is
not shown to the user, which is called as abstraction.

3. Can we achieve 100% abstraction using abstract class? If not, why?


No, we cannot because abstract class can contain abstract methods as well
as concrete methods.
(if a class as 1 or less then 1 abstract methods also the class can be made as
abstract class)

Inheritance:
1. Can I inherit private variables of parent class in child class?
No

2. What is the use of inheritance?


Inheritance is used to access the parent class variables and functions in
child class.
It also reduces code duplication

3. Is the constructor inherited to child classes?


No but the constructors of parent class can be invoked in child class.

4. Are final methods inherited to child classes?


Yes but you cannot override it.

5. Can I call / access final methods from child class?


No

6. Can I override final methods in the child class?


No they cannot be overridden or hidden.

7. How do you call a parent class constructor from a child class?


By using super() call

8. What is object class?


It is the parent most / superclass . It is the root of the class hierarchy.

9. If i don't want to inherit my class, what should i do?


1. Using the final keyword in class declaration
2. Making the class constructor private.
10. Can I inherit the final class?
No cannot be inherited or extended.

11. Why java doesn’t support multiple inheritance?


Because it can lead to diamond problem.

12. What is function ambiguity in java? Show one example


Confusion caused due to same function name in different class.
Say for example there is a parent class and a child class with the same
function(method) name. so jvm will be confused as to which functions variables
should be accessed first. This is function ambiguity in java.

13. How will you achieve multiple inheritance in java? Show one eg?
Implementing multiple interfaces in a class
Eg:
class A{
//java code
}
interface One{
//java code
}
interface Two{
//java code
}
class B extends A implements One, Two{
//java code
}

14. How many types of inheritances are there in java?


5 types
1. single level
A

2. multi level
A

B
C

3. hierarchial
A

B C D

4. multiple

A B

5. hybrid
A

B C

15. Which type of inheritance is not supported in java?


Multiple and hybrid.

16. What is the limitation or disadvantage of inheritance in java.


Child class becomes dependent on the parent class implementation.

17. Trainer can ask any coding based question on inheritance find output

Polymorphism:
1. Give one example for static polymorphism
Method Overloading
Eg:
class Sample{
public int m1(){
return 10;
}
public int m1(int x){
return 1000;
}
public int m1(String y){
return 10;
}
public int m1(int z, int r){
return 150;
}
}

2. Give one example for dynamic polymorphism


Method Overriding
Eg:
class Base{
public void f1(){
System.out.println(“Base function”);
}
}
class Derived extends Base{
public void f1(){
System.out.println(“Derived function”);
}
}

Method overloading
1. If 2 methods have the same name, same parameters, but different return type,
is it overloading or error?
Error because it doesn’t participate in method overloading coz of same
parameters and it considers it as normal methods, but normal methods can have
the same name but cannot have same parameters hence error

2. Can i overload constructor


Yes, same as function overloading.

3. Can i overload static methods


Yes, we can have two or more static methods with the same name but
different input parameters.

4. Can i overload final methods


No, final methods cannot be overridden or hidden.

5. How will you call overloaded methods, eg.


By passing different parameters.
Eg :
class M1{
public M1(int a ){
System.out.println(“M1”);
}
}
class M2 extends M1{
public M2(){
super(10);
System.out.println(“M2-1”);
}
public M2(char c){
this();
System.out.println(“M2-2”);
}
}
public class MyClass{
public static void main(String[] args){
M2 m = new M2(‘*’);
}
}

6. Trainer can give any code and ask if it is overloading or not.

Method overriding:
1. Can i override private methods of parent class in child class
No, private or static methods cannot be overridden.

2. Can i override abstract methods in child class


Child class must override all abstract methods of an abstract class.

3. Can i override parent class constructor in child class, why?


If we define parent class constructor in child class it will give compile
time error for return type and consider it a method.

4. If I don't want to override a parent class method in child class, what should I
do?
1. Using a static method
2. Using private access modifier
3. using default access modifier
4. using the final keyword method
5. What is the difference between private method and final method (as we can’t
override both methods in child class)?
Private Members Final
1. Even by creating object you 1. By creating object you can
cannot access it outside the access it outside the class
class 2. It can participate in
2. It cannot participate in inheritance (only methods)
inheritance
Final class cannot be
inherited but in normal class
final methods can be
inherited

6. Can I override parent class static methods in child class?


No

7. How do you call parent class over ridden method from child class method.
eg.
Using super() keyword
Eg :
class A{
public void fun(){
System.out.println(“Base function”);
}
}
class B extends A{
public void fun(){
super.fun();
System.out.println(“Derived function”);
}
}
public static void main(String[] args){
B b = new B();
b.fun();
}

8. Trainer can ask any overriding based code find output.


Static and non static:
1. How will you access static variables [or] static methods of a class? Show one
eg
Static methods are accessed using class name not object name.
(Static methods cannot access instance methods and variables.)
Eg :
class Demo{
static int y = 30;
static int m2(){
return 100;
}
}
public static void main(String[] args){
System.out.println(Demo.y);
System.out.println(Demo.m2());
}

2. How will you access non static variables [or] non static methods of a class?
Show one eg
Accessed using object name
Eg:
class Demo{
public int x = 20;
public int m1(){
return 10;
}
}
public static void main(String[] args){
Demo d = new Demo();
System.out.println(d.x);
d.m1();
}

3. Which is faster, static methods or instance methods. Why?


Static because it directly uses class name instead of object name

4. Why is the main() method static?


The main() method is static so that the JVM can invoke it without
instantiating the class. This also saves the unnecessary wastage of memory
which would have been used by the object declared only for calling the main()
method by the JVM

5. Can I access non-static variables inside a static method? how?


We cannot access non-static variables in static methods because non-
static variables can only be accessed by creating an instance of the class.

6. Trainer can ask any coding find output question

Abstract methods and abstract classes:


1. If I have 0 abstract methods in a class, can I make that class an abstract class?
Yes, even if there are no abstract methods in a class we can make the
class as abstract class.

2. Can I create an object for an abstract class?


No

3. How will you access methods (which have bodies) of an abstract class?
We need to extend and use child class object variable to access abstract
class methods.

4. Can I have a constructor in abstract class?


Yes

5. When will you use an abstract class, give one scenario with code
(same question can be asked as what is the use of abstract class)
1. Used when we have to share common functionalities with related
classes
2. It enforces child class to give body to a particular method
3. Avoids code duplication
Eg :
public abstract class A{
public abstract void f1();
public abstract int f2(int x);
}
public class B extends A{
public void f1(){
System.out.println(“Hi);
}
public int f2(int x){
System.out.println(“Bye”);
return 100;
}
}
public static void main(String[] args){
B b = new B();
b.f1();
b.f2(10);
}

6. When will you use an abstract method, give one scenario with code
(same question can be asked as what is the use of abstract method)
Using an abstract method in the code saves time. We can call the abstract
method wherever the method is necessary. Abstract class avoids the process of
writing the same code again. Abstraction is achieved by abstract methods.
Eg:
public abstract class A{
public abstract void f1();
public abstract int f2(int x);
}

7. Can I achieve complete or full abstraction with the help of abstract class?
Why if not?
No because it can also have concrete methods and also if there are even
zero abstract methods the class can be made as an abstract class.

8. Can I make an abstract class as a final class?


You must override an abstract method therefore abstract cannot be final

9. Take a parent class with few abstract methods, ask student to inherit into a
child class. Ask student to call the methods with object.
Eg:
public abstract class A{
public abstract void f1();
public abstract int f2(int x);
}
public class B extends A{
public void f1(){
System.out.println(“Hi);
}
public int f2(int x){
System.out.println(“Bye”);
return 100;
}
}
public static void main(String[] args){
B b = new B();
b.f1();
b.f2(10);
}

10. Trainer can ask any coding question on abstract method or class

Interface:
1. What is the use of interface (same question can be asked as when will you
use interface) give one scenario example with code
Interfaces lets us share common functionalities with unrelated classes.
Eg:
public interface I{
public void fun1();
public int fun2(int x);
}
class Imp implements I{
public void fun1(){
System.out.println(“Hi”);
}
public int fun2(int x){
Return x;
}
}
public static void main(String[] args){
Imp i = new Imp();
i.fun1();
int y = i.fun2(10);
System.out.println(y);
}

2. Does interface support multiple inheritance, show code


Yes
Eg:
interface One{
public void fun1();
}
interface Two{
public void fun2();
}
class MulInterface implements One,Two{
public void fun1(){
System.out.println(“Interface One”);
}
public void fun2(){
System.out.println(“Interface Two”);
}
}
public static void main(String[] args){
MulInterface mi = new MulInterface();
mi.fun1();
mi.fun2();
}

3. What is the access specifier used for the members of interfaces?


Public

4. Can we achieve complete or full abstraction with an interface? Why


Yes because only abstract methods and are used in interfaces
(information about the implementation is completely hidden from the user, thus
achieving 100% abstraction)

5. Can I implement multiple interfaces in a class? eg


Yes.
Refer answer 2

6. Give one real world example (not java) of interface?


ATM mechanism

7. Can one interface inherit other interface


Yes, The derived interface inherits the members from its base interfaces.
A class that implements a derived interface must implement all members in the
derived interface, including all members of the derived interfaces base interface

8. How will you implement an interface in a class and how will you call
methods.
Refer code in answer 1

9. Trainer can ask any coding question on interface

Access specifier:
1. Can I access protected variables in other packages?
We can protected variables in subclasses of other packages but not in
different classes of other packages

2. Can I access private variables in other classes?


No
(to access we have to use public getter methods)
Eg :
public class AccessPrivateVariables {

public static void main(String[] args) {


Specifiers s = new Specifiers();
int y = s.getx();
System.out.println(y);
}
}
class Specifiers{
private int x = 10;
public int getx() {
return 10;

}
}

3. Which access specifier is used for data security?


Private

4. Difference bw protected and default


Protected : It can be used in
1. The same class
2. Other classes of same package
3. Child classes of other package
Default : It can be used in
1. The same class
2. Other classes of same package

5. Trainer can ask any coding question on access specifier

Exceptions:
1. What is checked exception, give one eg.
Checked exceptions are exceptions which are to be handled by
programmer using try – catch block or throws clause
Eg for checked exceptions are: SQL Exception, IOException like
FileNotFoundException, SocketException etc

public class EgForFileNotfound{


public static void main(String[] args){
String path = “c:\\java\\abc.txt”;
try{
FileReader f = new FileReader(path);
}
catch(FileNotFoundException e){
System.out.println(“File doesn’t exist”);
}
}

2. What is unchecked exception, give one eg.


Programmer need not handle these kind of exceptions using try – catch
block and throws clause.
Eg :
Error like IOError, LinkageError, OutOfMemoryError and Runtime Exceptions
like ArithmeticException , ArrayIndexOutOfBounds Exceptions etc

3. If I don't want to handle an exception, what should I do. Show eg.


If I don’t want to handle an exception we can throw the exception in
parent method by using throws clause. We can use throws clause after writing
the signature of the function before starting the body after that we have write
that exception name.
Eg :
class Excep{
public void readMe(String path) throws FileNotFoundException{
FileReader fr = new FileReader(path);
}
}
public static void main(String[] args){
Excep e = new Excep();
try{
e.readMe(C:/Users/Admin/Desktop/read.txt”);
}
catch(FileNotFoundException f){
System.out.println(“File not found”);
f.printStackTrace();
}
}

4. If I use throws, and if an exception occurs in the current method, then what
will happen. Who is going to handle that exception?
When a method declares that it throws an exception, it is not required to
handle the exception. The caller of the method that throws exceptions is
required to handle the exception (or throw them to its caller and so on) so that
the flow of the program is maintained

5. What is the use of throw. eg


If we don’t know how to catch he exception using try-catch block then
we can throw that exception to parent method using throws clause.
Used to declare exceptions that can occur during the execution of a program.
Eg:
class Excep{
public void readMe(String path) throws FileNotFoundException{
FileReader fr = new FileReader(path);
}
}
public static void main(String[] args){
Excep e = new Excep();
try{
e.readMe(C:/Users/Admin/Desktop/read.txt”);
}
catch(FileNotFoundException f){
System.out.println(“File not found”);
f.printStackTrace();
}
}

6. How will you create custom exception. eg.

7. What happens if an exception occurs in the finally block? Will the finally
block be executed?
Yes a finally block is always executed whether the exception has
occurred or not.

8. If we use system.exit(), then finally block will be executed or not?


No , the finally block will always get executed unless there is an
abnormal program termination resulting from a jvm crash or from a call to
system.exit().

Collections & generics:


1. What is the use of collections
2. difference between array and collections
3. In which version java collections are introduced
4. What is the difference between collections and generics
5. Why generics are safe
6. difference between linked list and array list which is best
7. In which case linkedlist is better
8. Dif bw vector and arraylist
9. Dif bw hashtable and map
10. dif bw list and set [or] arraylist vs set
11. dif bw set and map
12. dif bw array and list
13. Dif bw list and map
14. Trainer can ask any coding question

Memory, garbage collection, threads and miscellaneous:


1. How many parts are there in memory
2. What is stored in stack
3. What is stored in heap
4. What is garbage collector
5. What is the meaning of un referenced objects
6. What is hashcode
7. What is synchronization
8. What is thread priority
9. What is main thread
10. What is set priority
11. What is jre vs jdk
12. What is the use of stack heap
13. What is current version of java
14. What is clone()
15. what is serializable interface
16. == vs equals()

You might also like