Wednesday, 10 February 2016

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.
real life example of abstraction
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 */
}

How to achieve Abstraction ?

There are two ways to achieve abstraction in java
  • Abstract class (0 to 100%)
  • Interface (Achieve 100% abstraction)
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
Encapsulation vs Data Abstraction
  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 overloading?
ans-If we have to perform one operation having same name of the method.
here we can say method name should be same and parameter should be diffrent that is called overloading.
                                or
Overloading in Java is the ability to create multiple methods of the same name, but with different 

Advantage of overloading?
1-We don’t have to create and remember different names for functions doing the same thing.
2-Flexibility-
Overloaded methods give programmers the flexibility to call a similar method for different types of data. If you are working on a mathematics program, for example, you could use overloading to create several "multiply" classes, each of which multiplies a different number of type of argument: the simplest "multiply(int a, int b)" multiplies two integers; the more complicated method "multiply(double a, int b, int c)" multiplies one double by two integers -- you could then call "multiply" on any combination of variables that you created an overloaded method for and receive the proper result.
Example-
// Java program to demonstrate working of method
// overloading in Java.
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));
    }
}
Output :
30
60
31.0


Q- What is overriding?
Ans-Declaring a method in subclass which is already present in super class is know as overriding.

Example-
// A Simple Java program to demonstrate
// method overriding in java
// Base Class
class Parent
{
    void show() { System.out.println("Parent's show()"); }
}
// Inherited class
class Child extends Parent
{
    // This method overrides show() of Parent
    @Override
    void show() { System.out.println("Child's show()"); }
}
// Driver class
class Main
{
    public static void main(String[] args)
    {
        // If a Parent type reference refers
        // to a Parent object, then Parent's
        // show is called
        Parent obj1 = new Parent();
        obj1.show();
        // If a Parent type reference refers
        // to a Child object Child's show()
        // is called. This is called RUN TIME
        // POLYMORPHISM.
        Parent obj2 = new Child();
        obj2.show();
    }
}
Output:
Parent's show()
Child's show()


Overriding vs Overloading :
    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.

Inheritance in Java



Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allow to inherit the features(fields and methods) of another class.
Important terminology:
  • Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
How to use inheritance in Java
The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class  
{  
   //methods and fields  
}  
  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  10. }  
  11. }  
 Programmer salary is:40000.0
 Bonus of programmer is:10000

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.



Can we overload a static method in Java? (answer)

Yes, you can overload a static method in Java. You can declare as many static methods of the same name.

Can we override static method in Java? (answer)
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. 
But, Yes, you can declare the same static method in a subclass, that will result in method hiding i.e. if you use reference variable of type subclass then new method will be called, but if you use reference variable of superclass than old method will be called.

Can we override a private method in Java? (answer)
No, you cannot. Since the private method is only accessible and visible inside the class

note:-Though, you can override them inside the inner class as they are accessible there.

Can we override the final method in Java? (answer)
No, you cannot override a final method in Java, final keyword with the method is to prevent method overriding. You use final when you don't want subclass changing the logic of your method by overriding it due to security reason. This is why String class is final in Java. This concept is also used in template design pattern where template method is made final to prevent overriding.


Can an interface extend more than one interface in Java?
Yes, an interface can extend more than one interface in Java, it's perfectly valid.


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.

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 you cannot use an abstract class without extending and making it a concrete class.

1 comment:

  1. All Data are copied from my website sitesbay.com

    https://www.sitesbay.com/java/java-abstraction

    ReplyDelete