Tuesday 21 May 2013

Core Java Basic Interview Questions Part-2 !



Interview Questions


 1. Question: - What is a class?

Answer: - A class is nothing but a description of a set of objects that represent the same category/kind of entity. Each class describes a specific type of object e.g. class Customer, class Employee, and class Bird
Every object is an instance of some class. A class can be treating as a template from which different objects can be created.

2. Question:- What is Encapsulation?

Answer:-  Encapsulation is a process of hiding the implementation details of the object with binding the data and methods into a single unit and keeping the data safe from outside world. Once the object is encapsulated, Its implementation details are not immediately accessible any more. Encapsulation hides the implementation of an abstraction from its clients.

Encapsulation can also be treat as a  concept through which we can protect variables, functions from outside access by the clients. Using encapsulation we can better manage the piece of code So that it will not create ripples on other parts of program due to change in preserved code. In Java we can completely encapsulate a member variable or method by using the private access-modifiers. Even we can use protected or public access-modifiers. Data hiding means we are providing security to data within the class. It allows us to hide, how the state of an object is represented and how the object’s method works.

Below is the way to achieve encapsulation:-
  • By protecting the instance variables i.e. making it private. Some methods also may be private. Constructors and public methods of a class serve as the interface to class’s clients.
  • Forcing the calling code to use public accessor method rather than directly using the instance variables.
  • Providing the setter and getter methods in order to access instance variables by the clients.

Advantage
  • Encapsulation provides flexibility, maintainability and extensibility.
  • It is providing the ability to make changes in our implementation code without breaking the code of others who are using our code.
  • Main motive is to hide implementation details behind a public programming interface.
  • It provides the controlling about accessing the code.
  • It helps to reduce dependencies among parts of the program.
  • It helps us to follow Factory Design pattern and Singleton design pattern.

Example to achieve Encapsulation:-

            package com.gaurav.encapsulation;

public class CustomerTransaction {

            // Trying to get Encapsulation by making the instance variables private
            private int custId;
            private String custName;
            private String transactionId;
            private double transactionAmount;
            private String bankName;
            private String accountNumber;

            /**

             * By making the constructor private we can also protect it from outside world.

             * Then In that case we have to create a getInstance() factory method which will return this 
             * class object.

             */
            public CustomerTransaction(int customerId, String customerName,
                                    String transactionID, double transactionAmt, String bankName,
                                    String accNum) {
                        this.custId = customerId;
                        this.custName = customerName;
                        this.transactionId = transactionID;
                        this.transactionAmount = transactionAmt;
                        this.bankName = bankName;
                        this.accountNumber = accNum;
            }

            /**
             * @return the custId
             */
            public int getCustId() {
                        return custId;
            }

            /**
             * @param custId
             *            the custId to set
             */
            public void setCustId(int custId) {
                        this.custId = custId;
            }

            /**
             * @return the custName
             */
            public String getCustName() {
                        return custName;
            }

            /**
             * @param custName
             *            the custName to set
             */
            public void setCustName(String custName) {
                        this.custName = custName;
            }

            /**
             * @return the transactionAmount
             */
            public double getTransactionAmount() {
                        return transactionAmount;
            }

            /**
             * @param transactionAmount
             *            the transactionAmount to set
             */
            public void setTransactionAmount(double transactionAmount) {
                        this.transactionAmount = transactionAmount;
            }

            /**
             * @return the bankName
             */
            public String getBankName() {
                        return bankName;
            }

            /**
             * @param bankName
             *            the bankName to set
             */
            public void setBankName(String bankName) {
                        this.bankName = bankName;
            }

            /**
             * @return the transactionId
             */
            public String getTransactionId() {
                        return transactionId;
            }

            /**
             * @param transactionId the transactionId to set
             */
            public void setTransactionId(String transactionId) {
                        this.transactionId = transactionId;
            }

            /**
             * @return the accountNumber
             */
            public String getAccountNumber() {
                        return accountNumber;
            }

            /**
             * @param accountNumber the accountNumber to set
             */
            public void setAccountNumber(String accountNumber) {
                        this.accountNumber = accountNumber;
            }

            public boolean getPaymentStatus() {
                        boolean TransactionFlag = false;
                        if (transactionAmount != 0)
                                    TransactionFlag = true;
                        return TransactionFlag;
            }
           
     
            /**
             * Note:- In this example, we see all instance variables are made private
             * for protecting it from direct access from outside.
             * If you want that from outside users can access these variables then the better
             * approach is to create setter and getters.
             * */
}


Encapsulated class Caller:-

package com.gaurav.encapsulation;

public class CallCustomerTransaction {
            public static void main(String args[]) {

                        int custId = 12345;
                        String custName = "KUMAR GAURAV";
                        String transactionID = "IAHDFC09876543";
                        double transactionAmount = 1999.75;
                        String bankName = "HDFC BANK";
                        String accountNumber = "5436758698";
                       
                        CustomerTransaction ct = new CustomerTransaction(custId, custName,
                                                transactionID, transactionAmount, bankName, accountNumber);

                        System.out.println(ct.getPaymentStatus());

                        ct.setCustId(354364);
                        ct.setCustName("SACHIN");
                        ct.setTransactionId("3254765987QAW");
                        ct.setTransactionAmount(0);
                        ct.setBankName("ICICI");
                        ct.setAccountNumber("425364758");

                        System.out.println(ct.getPaymentStatus());

            }

}

/**
 * Note:- CallCustomerTransaction class can't access instance variables of the
 * class CustomerTransaction , without going through the public accessor getter
 * and setter methods as those variables are marked as private and only accessor
 * methods are public.
 */

Here in ct.setCustName("SACHIN"), the name data “SACHIN” is bonded with the method setCustName, so it is nothing but Data Binding. We cannot directly access the instance variable “custName” declared in the encapsulated class CustomerTransaction from outside. So, it is nothing but Data Hiding and using both(Data Binding and Data Hiding) we are achieving Encapsulation. So we can say that Data Binding proceed towards the Data Hiding and Data Hiding proceed towards the Encapsulation.

 

3. Question:- What is Abstraction?

Answer:- We can achieve Abstraction during the design of the class. When designing a class we must provide a set of methods that accurately captures the behaviour of entities of that type. Abstraction is hiding the implementation details by providing a layer over the basic functionality. It’s a process of separating the presentation details from the implementation details. Abstractions provide an external view of the entity. How that interface is implemented is hidden from clients/Users. We can provide several layers of abstraction to a system.

Example related to Real world :- Think about a human body, Internally many complexities are there like how intestine works, how blood circulates inside body, how blood forms, how it fights with bacteria's but it hides each complexities and provides the outside view or external view with muscles and skin.

Example related to Java API W.R.T Interface :- About Map interface and we know about the implementation HashMap class which stores key-value pair and it searches based on keys and having other public methods for different manipulations, So we know only about method names and method behaviour but we don't know about How HashMap works? This is actually what abstraction means.

Example related to Java API W.R.T Abstract Class : - A very good example of Abstraction in Java API is abstract Number class. Signature is:-
  • public abstract class Number implements java.io.Serializable

This class contains below abstract methods
  • public abstract int intValue();
  • public abstract long longValue();
  • public abstract float floatValue();
  • public abstract double doubleValue();

This class is also having implemented methods like

  • public byte byteValue() {
               return (byte)intValue();
           }

  • public short shortValue() {
              return (short)intValue();
          }

The well known subclasses for this Number class is BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short classes. These classes are providing the concrete implementation of the abstract methods by hiding the internal complexities and providing the external view which users can use in their classes.


4. Question:- What is the difference between Encapsulation and Abstraction?


Answer:-
                  Difference between Encapsulation and Abstraction:-
  • We can achieve encapsulation using access modifiers in a class and on the other way we can achieve Abstraction using interface and Abstract class. In order to use interface or abstract class we need to extend and implement abstract method with concrete behavior.
  • Abstraction focuses on the outside view of an object where as Encapsulation prevents clients from inside accessing, where the behavior of the abstraction is implemented.
Or
 we can say that:-
  •  Abstraction is more about 'What a class can do'? (Refers a scheme/idea – like a Book Index).
  • Encapsulation is more about 'How to achieve that functionality'? (Refers an Implementation – like a Book Contents which is associated with Book index).


No comments:

Post a Comment