OOPS Concept Interview Question
--------------------------------------------------------------------------------------------------
1)What is oops concept with example?
a-abstraction
b-incapsulation
c-polymorphism
d-inheritance.
-------------------------------------------------------------------------------------------------
Q-What is abstraction?
Ans:-Abstraction.Means hinding of data.
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. For example, when you login to your Amazon account online, you enter your user_id and password and press login, what happens when you press login, how the input data sent to amazon server, how it gets verified is all abstracted away from the you.
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only important details are provided
to the user.
Another real life example of Abstraction is ATM Machine;
All are performing operations on the ATM machine like cash withdrawal, money transfer,
retrieve mini-statement…etc. but we can't know internal details about ATM.
Note: Data abstraction can be used to provide security for the data from the unauthorized methods.
Note: In Java language data abstraction can achieve using class.
Example of Abstraction:-
class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and
balance is required and remaining properties
are hidden for fund transfer method */
}
Q:How to achieve Abstraction ?
Ans:-There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (Achieve 100% abstraction)
----------------------------------------------------------------------------------------------------------
Q-What is interface?
ans:- interface is contract between client and developer.
note:-"interface contain common method prototype that will implemented by multiple subclasses."
real time senario example:-
suppose i have banking application... in banking application i have four module.
(1)saving a/c
(2)deposit a/c
(3)couurent a/c
(4)fixed deposit
so there is chance that all this module will be developed by deffrent-2 developer or diffrent-2 company
also there is a chance so what i want...
i want there are some method, some 20 method i have, that 20 methos should be same accors all the module,
saving a/c customer or developer also has to override the same methos or other developer also has to override.
"implementation may change but if they want to check the balance get the balance methos is there
its take account number as a perameter, return type is duble
withdraw method is there, deposit method is there.
so suppose these method prototype are common amoung multiple sub classe's"
note:- if you want to centralized common method prototype you can write inside the interface
so interface contain common method prototype that wil be implemented by multiple sub classe's
Example of Interface
interface Person
{
void run(); // abstract method
}
class A implements Person
{
public void run()
{
System.out.println("Run fast");
}
public static void main(String args[])
{
A obj = new A();
obj.run();
}
}
Output
Run fast
Multiple Inheritance using interface
Example
interface Developer
{
void disp();
}
interface Manager
{
void show();
}
class Employee implements Developer, Manager
{
public void disp()
{
System.out.println("Hello Good Morning");
}
public void show()
{
System.out.println("How are you ?");
}
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}
Output
Hello Good Morning
How are you ?
==========================================================================================================
Q:-Why we use Interface ?
Ans-• It is used to achieve fully abstraction.
• By using Interface, you can achieve multiple inheritance in java.
• It can be used to achieve loose coupling.
Properties of Interface:-
• It is implicitly abstract. So we no need to use the abstract keyword when declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
• Methods in an interface are implicitly public.
• All the data members of interface are implicitly public static final.
roles of interface:-
1:Interfaces should contain only abstract methods
2:-nterfaces are implemented by the class using ‘implements‘ keyword.
3:-By default, Every field of an interface is public, static and final,
You can’t change the value of a field once they are initialized. Because they are static and final.
4:-By default, All methods of an interface are public and
----------------------------------------------------------------------------------------------------------
Q:-When we use abstract and when Interface
Ans:-If we do not know about any things about implementation just we have requirement specification then
we should be go for Interface
If we are talking about implementation but not completely (partially implemented) then
we should be go for abstract.
Rules for implementation interface
• A class can implement more than one interface at a time.
• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, similarly to the way that a class can extend another class.
-------------------------------------------------------------------------------------------------------
Q-What is Abstract class in Java?
A class that is declared as abstract is known as abstract class.
or
abstract class that is having paritial implementation is called abstract class.
now in abstract class you can write abstract methos also concrete method now why to write concrete method.
there are some situation where multiple suclasses have some method behaviour is common
suppose print statement method is there its responsibility to take the
account number and print the statement
suppose this method behaviour is common in all the subclass
so why to write the same method body in all the subclasses
it will give code duplication problem
note:-in future if you want to change all the subclass's you have to modify so better what we can do
we can write that common method behaviour in the abstract class
note:-so we can say abstract class contain common methos behaviour
and concreate contaion specifig method behaviour
Syntax:
abstract class <class-name>{}
An abstract class is something which is incomplete and you cannot create instance of abstract class.
If you want to use it you need to make it complete or concrete by extending it.
A class is called concrete if it does not contain any abstract method and implements
all abstract method inherited from abstract class or interface
it has implemented or extended.
Why interface have no constructor ?
Because, constructor are used for eliminate the default values by user defined values,
but in case of interface all the data members are public static final that means all are constant
so no need to eliminate these values.
Other reason because constructor is like a method and it is concrete method and
interface does not have concrete method it have only abstract methods
that's why interface have no constructor.
-------------------------------------------------------------------------------------------------------------
Q-What is Incapsulation?
Ans:-Binding of data (variable and method ) in single unit.
Encapsulation can be achieved 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
Advantages of Encapsulation:
? Data Hiding: The user will have no idea about the inner implementation of the class.
It will not be visible to the user that how the class is storing values in the variables.
He only knows that we are passing the values to a setter method and variables are getting initialized
with that value.
Increased Flexibility: We can make the variables of the class as read-only or write-only
depending on our requirement. If we wish to make the variables as read-only then
we have to omit the setter methods like setName(), setAge() etc. from the above program or
if we wish to make the variables as write-only then we have to omit the get methods like getName(),
getAge() etc. from the above program
Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
// Java program to demonstrate encapsulation
public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
// get method for age to access
// private variable geekAge
public int getAge()
{
return geekAge;
}
// get method for name to access
// private variable geekName
public String getName()
{
return geekName;
}
// get method for roll to access
// private variable geekRoll
public int getRoll()
{
return geekRoll;
}
// set method for age to access
// private variable geekage
public void setAge( int newAge)
{
geekAge = newAge;
}
// set method for name to access
// private variable geekName
public void setName(String newName)
{
geekName = newName;
}
// set method for roll to access
// private variable geekRoll
public void setRoll( int newRoll)
{
geekRoll = newRoll;
}
}
In the above program the class EncapsulateDemo is encapsulated as the variables are declared as private. The get methods like getAge() , getName() , getRoll() are set as public, these methods are used to access these variables. The setter methods like setName(), setAge(), setRoll() are also declared as public and are used to set the values of the variables.
The program to access variables of the class EncapsulateDemo is shown below:
public class TestEncapsulation
{
public static void main (String[] args)
{
Encapsulate obj = new Encapsulate();
// setting values of the variables
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// Displaying values of the variables
System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());
// Direct access of geekRoll is not possible
// due to encapsulation
// System.out.println("Geek's roll: " + obj.geekName);
}
}
Output:
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51
Q:-Encapsulation vs Data Abstraction
Ans:-1. Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon the data, data abstraction deals with exposing the interface to the user and hiding the details of implementation.
3. Encapsulation is not providing full security because we can access private member of the class using reflection API, but in case of Abstraction we can't access static, abstract data member of a class.
---------------------------------------------------------------------------------------------------------
Q-What is polymorphism?
Ans-Ablity to take more than one form that is called polymorphism
Example of polymorphism;-
import java.util.ArrayList;
import java.util.List;
abstract class Pet{
public abstract void makeSound();
}
class Cat extends Pet{
@Override
public void makeSound() {
System.out.println("Meow");
}
}
class Dog extends Pet{
@Override
public void makeSound() {
System.out.println("Woof");
}
}
Let's test How Polymorphism concept work in Java:
/**
*
* Java program to demonstrate What is Polymorphism
* @author Javin Paul
*/
public class PolymorphismDemo{
public static void main(String args[]) {
//Now Pet will show How Polymorphism work in Java
List<Pet> pets = new ArrayList<Pet>();
pets.add(new Cat());
pets.add(new Dog());
//pet variable which is type of Pet behave different based
//upon whether pet is Cat or Dog
for(Pet pet : pets){
pet.makeSound();
}
}
}
Output:
Meow
Woof
We can achieve polymorphism in two way?
1-overloading
2-overriding.
--------------------------------------------------------------------------------------------------------
Q- What is overlaoding?
Ans:-If you want to perform one operation having same name of the method is called overlaoding
another word method nae should be same but signature or parameter should be diffrent
Overloading is an example of compiler-time polymorphism
Advantage of method overloading
Method overloading increases the readability of the program.
s
example:-
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
---------------------------------------------------
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
---------------------------------------------------
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
------------------------------------------------------------
Q:- What is overriding?
Ans:-Declaring methiod in subclass which is alredy present in super class
Lets take a simple example to understand this. We have two classes:
A child class B and a parent A . The B class extends A class.
Both the classes have a common method void eat().
B class is giving its own implementation to the eat() method
or in other words it is overriding the eat() method.
The purpose of Method Overriding is clear here.
Child class wants to give its own implementation so that when it calls this method, it prints B is eating instead of A is eating.
The main advantage of method overriding is that the class can give its own specific implementation
to a inherited method without even modifying the parent class code.
Method Overriding is an example of runtime polymorphism.
When a parent class reference points to the child class object then the call to the overridden method is determined at runtime,
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp();
/* When parent class reference refers to the child class object
* then the overriding method (method of child class) is called.
* This is called dynamic method dispatch and runtime polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:
disp() method of parent class
disp() method of Child class
Rules for method overriding:
1-In java, a method can only be written in Subclass, not in same class.
2-The argument list should be exactly the same as that of the overridden method.
3-The return type should be the same or a subtype of the return type declared
in the original overridden method in the super class.
4-The access level cannot be more restrictive than the overridden method’s access level.
5-For example: if the super class method is declared public then the over-ridding
method in the sub class cannot be either private or protected.
6-Instance methods can be overridden only if they are inherited by the subclass.
7-A method declared final cannot be overridden.
8-A method declared static cannot be overridden but can be re-declared.
9-If a method cannot be inherited then it cannot be overridden.
10-A subclass within the same package as the instance’s
superclass can override any superclass method that is not declared private or final.
11-A subclass in a different package can only override the non-final methods declared public or protected.
12-An overriding method can throw any uncheck exceptions, regardless of whether
the overridden method throws exceptions or not.
13-However the overriding method should not throw checked exceptions that are new or broader
than the ones declared by the overridden method. The overriding method can throw narrower or
fewer exceptions than the overridden method.
14-Constructors cannot be overridden.
-------------------------------------------------------------------------------------------------------
Q:-Overriding vs Overloading :
Ans:-
1-Overloading is about same method have different signatures. Overriding is about same method,
same signature but different classes connected through inheritance.
2-Overloading is an example of compiler-time polymorphism and overriding is an
example of run time polymorphism
-------------------------------------------------------------------------------------------------------
Q:- What is Inheritance?
Ans:-It is the mechanism which one class is allow to inherit the features(fields and methods) of another class.
-------------------------------------------------------------------------------------------------------
Q:-Why use Inheritance ?
• For Method Overriding (used for Runtime Polymorphism).
• It's main uses are to enable polymorphism and to be able to reuse code for different classes
by putting it in a common super class
• For code Re-usability
Advantage of inheritance
If we develop any application using concept of Inheritance than that application have following advantages,
• Application development time is less.
• Application take less memory.
• Application execution time is less.
• Application performance is enhance (improved).
• Redundancy (repetition) of the code is reduced or minimized so that
we get consistence results and less storage cost.
-------------------------------------------------------------------------------------------------------
Q:-Can we overload a static method in Java? (answer)
Ans-Yes, you can overload a static method in Java. You can declare as many static methods of the same name.
------------------------------------------------------------------------------------------------------
Q:-Can we override static method in Java? (answer)
Ans-No, you cannot override a static method because it's not bounded to an object. Instead,
static methods belong to a class and resolved at compile time using the type of reference variable
Can a class extend more than one class in Java?
No, a class can only extend another class because Java doesn't support multiple inheritances but yes,
it can implement multiple interfaces.
-------------------------------------------------------------------------------------------------
Q:-Can we make a class both final and abstract at the same time? (answer)
ans-no they are exactly opposite of each other. A final class in Java cannot be extended and
-------------------------------------------------------------------------------------------------
Q:Can an interface extend more than one interface in Java?
ans-Yes, an interface can extend more than one interface in Java, it's perfectly valid.
you cannot use an abstract class without extending and making it a concrete class.
==================================================================================================
Q:- How many Type of Exception?
Ans;-
1)Checked Exception
2)Un-Checked Exception
1:-Checked Exception
Checked Exception-"if you code inside the method or constructor throwing some exception and
if that exception is checked by compiler, compiler is forcing you to report about the exception
by writting by try and catch block or by using throws keyword is called checked exception".
are the exception which checked at compile-time.
These exception are directly sub-class of java.lang.Exception class.
Only for remember: Checked means checked by compiler so checked exception are checked at compile-time.
Example:- classNotFound,fileNotFound,
2:-Un-Checked Exception
Un-Checked Exception-means this is aslo called runtime Exception,
if some code inside the method throwing exception and compiler is not telling anything
wheather exception you want to report or dont report, compiler is not informing anything is called
unchecked exception.are the exception both identifies or raised at run time.
These exception are directly sub-class of java.lang.RuntimeException class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-checked exception are checked at run-time
not compile time.
Example:- nullPointerException, arrayOutOfBoundxception
==========================================================================================================
Q:-Difference between checked Exception and un-checked Exception
Checked Exception Un-Checked Exception
1- checked Exception are checked at compile time un-checked Exception are checked at run time
OOPS Interview Question and Answer
==========================================================================================================
Q:-How to create User define Exception or Custom Exception in Java?
Ans:-
If any exception is design by the user known as user defined or Custom Exception.
Custom Exception is created by user.
Rules to design user defined Exception
1. Create a package with valid user defined name.
2. Create any user defined class.
3. Make that user defined class as derived class of Exception or RuntimeException class.
4. Declare parametrized constructor with string variable.
5. call super class constructor by passing string variable within the derived class constructor.
6. Save the program with public class name.java
3
e.g:-FileNotFoundException, e.g.:-NumberNotFoundException etc.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
--------------------------------------------------------------------------------------------------
1)What is oops concept with example?
a-abstraction
b-incapsulation
c-polymorphism
d-inheritance.
-------------------------------------------------------------------------------------------------
Q-What is abstraction?
Ans:-Abstraction.Means hinding of data.
Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user. For example, when you login to your Amazon account online, you enter your user_id and password and press login, what happens when you press login, how the input data sent to amazon server, how it gets verified is all abstracted away from the you.
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only important details are provided
to the user.
Another real life example of Abstraction is ATM Machine;
All are performing operations on the ATM machine like cash withdrawal, money transfer,
retrieve mini-statement…etc. but we can't know internal details about ATM.
Note: Data abstraction can be used to provide security for the data from the unauthorized methods.
Note: In Java language data abstraction can achieve using class.
Example of Abstraction:-
class Customer
{
int account_no;
float balance_Amt;
String name;
int age;
String address;
void balance_inquiry()
{
/* to perform balance inquiry only account number
is required that means remaining properties
are hidden for balance inquiry method */
}
void fund_Transfer()
{
/* To transfer the fund account number and
balance is required and remaining properties
are hidden for fund transfer method */
}
Q:How to achieve Abstraction ?
Ans:-There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (Achieve 100% abstraction)
----------------------------------------------------------------------------------------------------------
Q-What is interface?
ans:- interface is contract between client and developer.
note:-"interface contain common method prototype that will implemented by multiple subclasses."
real time senario example:-
suppose i have banking application... in banking application i have four module.
(1)saving a/c
(2)deposit a/c
(3)couurent a/c
(4)fixed deposit
so there is chance that all this module will be developed by deffrent-2 developer or diffrent-2 company
also there is a chance so what i want...
i want there are some method, some 20 method i have, that 20 methos should be same accors all the module,
saving a/c customer or developer also has to override the same methos or other developer also has to override.
"implementation may change but if they want to check the balance get the balance methos is there
its take account number as a perameter, return type is duble
withdraw method is there, deposit method is there.
so suppose these method prototype are common amoung multiple sub classe's"
note:- if you want to centralized common method prototype you can write inside the interface
so interface contain common method prototype that wil be implemented by multiple sub classe's
Example of Interface
interface Person
{
void run(); // abstract method
}
class A implements Person
{
public void run()
{
System.out.println("Run fast");
}
public static void main(String args[])
{
A obj = new A();
obj.run();
}
}
Output
Run fast
Multiple Inheritance using interface
Example
interface Developer
{
void disp();
}
interface Manager
{
void show();
}
class Employee implements Developer, Manager
{
public void disp()
{
System.out.println("Hello Good Morning");
}
public void show()
{
System.out.println("How are you ?");
}
public static void main(String args[])
{
Employee obj=new Employee();
obj.disp();
obj.show();
}
}
Output
Hello Good Morning
How are you ?
==========================================================================================================
Q:-Why we use Interface ?
Ans-• It is used to achieve fully abstraction.
• By using Interface, you can achieve multiple inheritance in java.
• It can be used to achieve loose coupling.
Properties of Interface:-
• It is implicitly abstract. So we no need to use the abstract keyword when declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
• Methods in an interface are implicitly public.
• All the data members of interface are implicitly public static final.
roles of interface:-
1:Interfaces should contain only abstract methods
2:-nterfaces are implemented by the class using ‘implements‘ keyword.
3:-By default, Every field of an interface is public, static and final,
You can’t change the value of a field once they are initialized. Because they are static and final.
4:-By default, All methods of an interface are public and
----------------------------------------------------------------------------------------------------------
Q:-When we use abstract and when Interface
Ans:-If we do not know about any things about implementation just we have requirement specification then
we should be go for Interface
If we are talking about implementation but not completely (partially implemented) then
we should be go for abstract.
Rules for implementation interface
• A class can implement more than one interface at a time.
• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, similarly to the way that a class can extend another class.
-------------------------------------------------------------------------------------------------------
Q-What is Abstract class in Java?
A class that is declared as abstract is known as abstract class.
or
abstract class that is having paritial implementation is called abstract class.
now in abstract class you can write abstract methos also concrete method now why to write concrete method.
there are some situation where multiple suclasses have some method behaviour is common
suppose print statement method is there its responsibility to take the
account number and print the statement
suppose this method behaviour is common in all the subclass
so why to write the same method body in all the subclasses
it will give code duplication problem
note:-in future if you want to change all the subclass's you have to modify so better what we can do
we can write that common method behaviour in the abstract class
note:-so we can say abstract class contain common methos behaviour
and concreate contaion specifig method behaviour
Syntax:
abstract class <class-name>{}
An abstract class is something which is incomplete and you cannot create instance of abstract class.
If you want to use it you need to make it complete or concrete by extending it.
A class is called concrete if it does not contain any abstract method and implements
all abstract method inherited from abstract class or interface
it has implemented or extended.
Why interface have no constructor ?
Because, constructor are used for eliminate the default values by user defined values,
but in case of interface all the data members are public static final that means all are constant
so no need to eliminate these values.
Other reason because constructor is like a method and it is concrete method and
interface does not have concrete method it have only abstract methods
that's why interface have no constructor.
-------------------------------------------------------------------------------------------------------------
Q-What is Incapsulation?
Ans:-Binding of data (variable and method ) in single unit.
Encapsulation can be achieved 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
Advantages of Encapsulation:
? Data Hiding: The user will have no idea about the inner implementation of the class.
It will not be visible to the user that how the class is storing values in the variables.
He only knows that we are passing the values to a setter method and variables are getting initialized
with that value.
Increased Flexibility: We can make the variables of the class as read-only or write-only
depending on our requirement. If we wish to make the variables as read-only then
we have to omit the setter methods like setName(), setAge() etc. from the above program or
if we wish to make the variables as write-only then we have to omit the get methods like getName(),
getAge() etc. from the above program
Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
// Java program to demonstrate encapsulation
public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;
// get method for age to access
// private variable geekAge
public int getAge()
{
return geekAge;
}
// get method for name to access
// private variable geekName
public String getName()
{
return geekName;
}
// get method for roll to access
// private variable geekRoll
public int getRoll()
{
return geekRoll;
}
// set method for age to access
// private variable geekage
public void setAge( int newAge)
{
geekAge = newAge;
}
// set method for name to access
// private variable geekName
public void setName(String newName)
{
geekName = newName;
}
// set method for roll to access
// private variable geekRoll
public void setRoll( int newRoll)
{
geekRoll = newRoll;
}
}
In the above program the class EncapsulateDemo is encapsulated as the variables are declared as private. The get methods like getAge() , getName() , getRoll() are set as public, these methods are used to access these variables. The setter methods like setName(), setAge(), setRoll() are also declared as public and are used to set the values of the variables.
The program to access variables of the class EncapsulateDemo is shown below:
public class TestEncapsulation
{
public static void main (String[] args)
{
Encapsulate obj = new Encapsulate();
// setting values of the variables
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// Displaying values of the variables
System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());
// Direct access of geekRoll is not possible
// due to encapsulation
// System.out.println("Geek's roll: " + obj.geekName);
}
}
Output:
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51
Q:-Encapsulation vs Data Abstraction
Ans:-1. Encapsulation is data hiding(information hiding) while Abstraction is detail hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon the data, data abstraction deals with exposing the interface to the user and hiding the details of implementation.
3. Encapsulation is not providing full security because we can access private member of the class using reflection API, but in case of Abstraction we can't access static, abstract data member of a class.
---------------------------------------------------------------------------------------------------------
Q-What is polymorphism?
Ans-Ablity to take more than one form that is called polymorphism
Example of polymorphism;-
import java.util.ArrayList;
import java.util.List;
abstract class Pet{
public abstract void makeSound();
}
class Cat extends Pet{
@Override
public void makeSound() {
System.out.println("Meow");
}
}
class Dog extends Pet{
@Override
public void makeSound() {
System.out.println("Woof");
}
}
Let's test How Polymorphism concept work in Java:
/**
*
* Java program to demonstrate What is Polymorphism
* @author Javin Paul
*/
public class PolymorphismDemo{
public static void main(String args[]) {
//Now Pet will show How Polymorphism work in Java
List<Pet> pets = new ArrayList<Pet>();
pets.add(new Cat());
pets.add(new Dog());
//pet variable which is type of Pet behave different based
//upon whether pet is Cat or Dog
for(Pet pet : pets){
pet.makeSound();
}
}
}
Output:
Meow
Woof
We can achieve polymorphism in two way?
1-overloading
2-overriding.
--------------------------------------------------------------------------------------------------------
Q- What is overlaoding?
Ans:-If you want to perform one operation having same name of the method is called overlaoding
another word method nae should be same but signature or parameter should be diffrent
Overloading is an example of compiler-time polymorphism
Advantage of method overloading
Method overloading increases the readability of the program.
s
example:-
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
---------------------------------------------------
Q) Why Method Overloading is not possible by changing the return type of method only?
In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
---------------------------------------------------
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
class TestOverloading4{
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}
}
------------------------------------------------------------
Q:- What is overriding?
Ans:-Declaring methiod in subclass which is alredy present in super class
Lets take a simple example to understand this. We have two classes:
A child class B and a parent A . The B class extends A class.
Both the classes have a common method void eat().
B class is giving its own implementation to the eat() method
or in other words it is overriding the eat() method.
The purpose of Method Overriding is clear here.
Child class wants to give its own implementation so that when it calls this method, it prints B is eating instead of A is eating.
The main advantage of method overriding is that the class can give its own specific implementation
to a inherited method without even modifying the parent class code.
Method Overriding is an example of runtime polymorphism.
When a parent class reference points to the child class object then the call to the overridden method is determined at runtime,
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp();
/* When parent class reference refers to the child class object
* then the overriding method (method of child class) is called.
* This is called dynamic method dispatch and runtime polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:
disp() method of parent class
disp() method of Child class
Rules for method overriding:
1-In java, a method can only be written in Subclass, not in same class.
2-The argument list should be exactly the same as that of the overridden method.
3-The return type should be the same or a subtype of the return type declared
in the original overridden method in the super class.
4-The access level cannot be more restrictive than the overridden method’s access level.
5-For example: if the super class method is declared public then the over-ridding
method in the sub class cannot be either private or protected.
6-Instance methods can be overridden only if they are inherited by the subclass.
7-A method declared final cannot be overridden.
8-A method declared static cannot be overridden but can be re-declared.
9-If a method cannot be inherited then it cannot be overridden.
10-A subclass within the same package as the instance’s
superclass can override any superclass method that is not declared private or final.
11-A subclass in a different package can only override the non-final methods declared public or protected.
12-An overriding method can throw any uncheck exceptions, regardless of whether
the overridden method throws exceptions or not.
13-However the overriding method should not throw checked exceptions that are new or broader
than the ones declared by the overridden method. The overriding method can throw narrower or
fewer exceptions than the overridden method.
14-Constructors cannot be overridden.
-------------------------------------------------------------------------------------------------------
Q:-Overriding vs Overloading :
Ans:-
1-Overloading is about same method have different signatures. Overriding is about same method,
same signature but different classes connected through inheritance.
2-Overloading is an example of compiler-time polymorphism and overriding is an
example of run time polymorphism
-------------------------------------------------------------------------------------------------------
Q:- What is Inheritance?
Ans:-It is the mechanism which one class is allow to inherit the features(fields and methods) of another class.
-------------------------------------------------------------------------------------------------------
Q:-Why use Inheritance ?
• For Method Overriding (used for Runtime Polymorphism).
• It's main uses are to enable polymorphism and to be able to reuse code for different classes
by putting it in a common super class
• For code Re-usability
Advantage of inheritance
If we develop any application using concept of Inheritance than that application have following advantages,
• Application development time is less.
• Application take less memory.
• Application execution time is less.
• Application performance is enhance (improved).
• Redundancy (repetition) of the code is reduced or minimized so that
we get consistence results and less storage cost.
-------------------------------------------------------------------------------------------------------
Q:-Can we overload a static method in Java? (answer)
Ans-Yes, you can overload a static method in Java. You can declare as many static methods of the same name.
------------------------------------------------------------------------------------------------------
Q:-Can we override static method in Java? (answer)
Ans-No, you cannot override a static method because it's not bounded to an object. Instead,
static methods belong to a class and resolved at compile time using the type of reference variable
Can a class extend more than one class in Java?
No, a class can only extend another class because Java doesn't support multiple inheritances but yes,
it can implement multiple interfaces.
-------------------------------------------------------------------------------------------------
Q:-Can we make a class both final and abstract at the same time? (answer)
ans-no they are exactly opposite of each other. A final class in Java cannot be extended and
-------------------------------------------------------------------------------------------------
Q:Can an interface extend more than one interface in Java?
ans-Yes, an interface can extend more than one interface in Java, it's perfectly valid.
you cannot use an abstract class without extending and making it a concrete class.
==================================================================================================
Q:- How many Type of Exception?
Ans;-
1)Checked Exception
2)Un-Checked Exception
1:-Checked Exception
Checked Exception-"if you code inside the method or constructor throwing some exception and
if that exception is checked by compiler, compiler is forcing you to report about the exception
by writting by try and catch block or by using throws keyword is called checked exception".
are the exception which checked at compile-time.
These exception are directly sub-class of java.lang.Exception class.
Only for remember: Checked means checked by compiler so checked exception are checked at compile-time.
Example:- classNotFound,fileNotFound,
2:-Un-Checked Exception
Un-Checked Exception-means this is aslo called runtime Exception,
if some code inside the method throwing exception and compiler is not telling anything
wheather exception you want to report or dont report, compiler is not informing anything is called
unchecked exception.are the exception both identifies or raised at run time.
These exception are directly sub-class of java.lang.RuntimeException class.
Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-checked exception are checked at run-time
not compile time.
Example:- nullPointerException, arrayOutOfBoundxception
==========================================================================================================
Q:-Difference between checked Exception and un-checked Exception
Checked Exception Un-Checked Exception
1- checked Exception are checked at compile time un-checked Exception are checked at run time
OOPS Interview Question and Answer
==========================================================================================================
Q:-How to create User define Exception or Custom Exception in Java?
Ans:-
If any exception is design by the user known as user defined or Custom Exception.
Custom Exception is created by user.
Rules to design user defined Exception
1. Create a package with valid user defined name.
2. Create any user defined class.
3. Make that user defined class as derived class of Exception or RuntimeException class.
4. Declare parametrized constructor with string variable.
5. call super class constructor by passing string variable within the derived class constructor.
6. Save the program with public class name.java
3
e.g:-FileNotFoundException, e.g.:-NumberNotFoundException etc.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
No comments:
Post a Comment