Saturday, 15 April 2017

Javaforinterview: Serialization uses and example

Javaforinterview: Serialization uses and example: Serialization is the process of converting an object's and its references objects to a sequence of bytes, as well as the process of reb...

Serialization uses and example

Serialization is the process of converting an object's and its references objects to a sequence of bytes, as well as the process of rebuilding those bytes into  object .in simple words Converting an object to bytes and bytes back to object.
Serialization is used when you want to persist the object. It is also used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In general, serialization is used when we want the object to exist beyond the lifetime of the JVM.


Here are some uses of serialization
  • To persist data for future use.
  • To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
  • To "flatten" an object into array of bytes in memory.
  • To store user session in Web applications.
  • To send objects between the servers in a cluster

A Java object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.ExternalizableDeserialization is the process of converting the serialized form of an object back into a copy of the object.




Example:

import java.io.Serializable;

public class Person implements Serializable {
        private String firstName;
        private String lastName;
        // stupid example for transient
        transient private Thread myThread;

        public Person(String firstName, String lastName) {
                this.firstName = firstName;
                this.lastName = lastName;
                this.myThread = new Thread();
        }

        public String getFirstName() {
                return firstName;
        }

        public void setFirstName(String firstName) {
                this.firstName = firstName;
        }

        public String getLastName() {
                return lastName;
        }

        public void setLastName(String lastName) {
                this.lastName = lastName;
        }

        @Override
        public String toString() {
                return "Person [firstName=" + firstName + ", lastName=" + lastName
                                + "]";
        }

}

The following code example show you how you can serializable and de-serializable this object.



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
        public static void main(String[] args) {
                String filename = "time.ser";
                Person p = new Person("Sam", "R");

                // save the object to file
                FileOutputStream fos = null;
                ObjectOutputStream out = null;
                try {
                        fos = new FileOutputStream(filename);
                        out = new ObjectOutputStream(fos);
                        out.writeObject(p);

                        out.close();
                } catch (Exception ex) {
                        ex.printStackTrace();
                }
                // read the object from file
                // save the object to file
                FileInputStream fis = null;
                ObjectInputStream in = null;
                try {
                        fis = new FileInputStream(filename);
                        in = new ObjectInputStream(fis);
                        p = (Person) in.readObject();
                        in.close();
                } catch (Exception ex) {
                        ex.printStackTrace();
                }
                System.out.println(p);
        }
}

Monday, 20 March 2017

Exception Handling

 Exception Handling with an example?


Exception Handling helps us to recover from an unexpected situations – File not found or network connection is down. The important part in exception handling is the try – catch block. Look at the example below. When exception is handled in a method, the calling methods will not need worry about that exception. Since Exception Handling is added in the method method2, the exception did not propogate to method1 i.e. method1 does not know about the exception in method2.

    public static void main(String[] args) {

        method1();

        System.out.println("Line after Exception - Main");

    }

 

    private static void method1() {

        method2();

        System.out.println("Line after Exception - Method 1");

    }

 

    private static void method2() {

        try {

            String str = null;

            str.toString();

            System.out.println("Line after Exception - Method 2");

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE

            System.out.println("Exception Handled - Method 2");

        }

    }

Program Output


Exception Handled - Method 2

Line after Exception - Method 1

Line after Exception - Main

Few important things to remember from this example.

·         If exception is handled, it does not propogate further.

·         In a try block, the lines after the line throwing the exception are not executed.

What is the use of finally block in Exception Handling?


When an exception happens, the code after the line throwing exception is not executed. If code for things like closing a connection is present in these lines of code, it is not executed. This leads to connection and other resource leaks.

Code written in finally block is executed even when there is an exception.

Consider the example below. This is code without a finally block . We have Connection class with open and close methods. An exception happens in the main method. The connection is not closed because there is no finally block.Connection that is opened is not closed. This results in a dangling (un-closed) connection.Finally block is used when code needs to be executed irrespective of whether an exception is thrown.

class Connection {

    void open() {

        System.out.println("Connection Opened");

    }

 

    void close() {

        System.out.println("Connection Closed");

    }

}

 

public class ExceptionHandlingExample1 {

 

    public static void main(String[] args) {

        try {

            Connection connection = new Connection();

            connection.open();

 

            // LOGIC

            String str = null;

            str.toString();

 

            connection.close();

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE- BAD PRACTICE

            System.out.println("Exception Handled - Main");

        }

    }

}

Output

Connection Opened

Exception Handled - Main

Let us now move connection.close(); into a finally block. Also connection declaration is moved out of the try block to make it visible in the finally block. Connection is closed even when exception is thrown. This is because connection.close() is called in the finally block. Finally block is always executed (even when an exception is thrown). So, if we want some code to be always executed we can move it to finally block.

    public static void main(String[] args) {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC

            String str = null;

            str.toString();

 

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE - BAD PRACTICE

            System.out.println("Exception Handled - Main");

        } finally {

            connection.close();

        }

    }

Output

Connection Opened

Exception Handled - Main

Connection Closed

In what kind of scenarios, a finally block is not executed?


Code in finally is NOT executed only in two situations.

·         If exception is thrown in finally.

·         If JVM Crashes in between (for example, System.exit()).

Is a finally block executed even when there is a return statement in the try block?


Yes. In the example below, connection.close() method is called even though there is a return in the catch block.

private static void method2() {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC    

            String str = null;

            str.toString();

            return;

        } catch (Exception e) {

            // NOT PRINTING EXCEPTION TRACE - BAD PRACTICE

            System.out.println("Exception Handled - Method 2");

            return;

        } finally {

            connection.close();

        }

    }

Is a try block without corresponding catch block allowed?


Yes. try without a catch is allowed. Example below.

private static void method2() {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC

            String str = null;

            str.toString();

        } finally {

            connection.close();

        }

    }

However a try block without both catch and finally is NOT allowed until before Java 7. Below method would give a Compilation Error!! (End of try block).

    private static void method2() {

        Connection connection = new Connection();

        connection.open();

        try {

            // LOGIC

            String str = null;

            str.toString();

        }//COMPILER ERROR!!

    }

With Java 7, for try blocks doing automatic resource management - it is allowed not to have both catch and finally.

  try (FileInputStream input = new FileInputStream("file.txt")) {

   int data = input.read();

   while (data != -1) {

    System.out.print((char) data);

    data = input.read();

   }

  }

 

Explain the hierarchy of Exception related classes in Java?


Throwable is the highest level of Error Handling classes.

Below class definitions show the pre-defined exception hierarchy in Java.

//Pre-defined Java Classes

class Error extends Throwable{}

class Exception extends Throwable{}

class RuntimeException extends Exception{}

Below class definitions show creation of a programmer defined exception in Java.

//Programmer defined classes

class CheckedException1 extends Exception{}

class CheckedException2 extends CheckedException1{}

 

class UnCheckedException extends RuntimeException{}

class UnCheckedException2 extends UnCheckedException{}

What is difference between an Error and an Exception?


Error is used in situations when there is nothing a programmer can do about an error. Ex: StackOverflowError, OutOfMemoryError. Exception is used when a programmer can handle the exception.

What is the difference between a Checked Exception and an Un-Checked Exception?


RuntimeException and classes that extend RuntimeException are called unchecked exceptions. For Example: RuntimeException,UnCheckedException,UnCheckedException2 are unchecked or RunTime Exceptions. There are subclasses of RuntimeException (which means they are subclasses of Exception also.)

Other Exception Classes (which don’t fit the earlier definition). These are also called Checked Exceptions. Exception, CheckedException1,CheckedException2 are checked exceptions. They are subclasses of Exception which are not subclasses of RuntimeException.

How do you throw a Checked Exception from a Method?


Consider the example below. The method addAmounts throws a new Exception. However, it gives us a compilation error because Exception is a Checked Exception.

All classes that are not RuntimeException or subclasses of RuntimeException but extend Exception are called CheckedExceptions. The rule for CheckedExceptions is that they should be handled or thrown. Handled means it should be completed handled - i.e. not throw out of the method. Thrown means the method should declare that it throws the exception

Example without throws: Does NOT compile


class AmountAdder {

    static Amount addAmounts(Amount amount1, Amount amount2) {

        if (!amount1.currency.equals(amount2.currency)) {

            throw new Exception("Currencies don't match");// COMPILER ERROR!                // Unhandled exception type Exception

        }

        return new Amount(amount1.currency, amount1.amount + amount2.amount);

    }

}

Example with throws definition


Let's look at how to declare throwing an exception from a method.

Look at the line "static Amount addAmounts(Amount amount1, Amount amount2) throws Exception". This is how we declare that a method throws Exception.

class AmountAdder {

    static Amount addAmounts(Amount amount1, Amount amount2) throws Exception {

        if (!amount1.currency.equals(amount2.currency)) {

            throw new Exception("Currencies don't match");

        }

        return new Amount(amount1.currency, amount1.amount + amount2.amount);

    }

}

How do you create a Custom Exception Classes?


We can create a custom exception by extending Exception class or RuntimeException class. If we extend Exception class, it will be a checked exception class. If we extend RuntimeException class, then we create an unchecked exception class.

Example


class CurrenciesDoNotMatchException extends Exception{

}

Let’s now create some sample code to use CurrenciesDoNotMatchException. Since it is a checked exception we need do two things a. throw new CurrenciesDoNotMatchException(); b. throws CurrenciesDoNotMatchException (in method declaration).

class AmountAdder {

    static Amount addAmounts(Amount amount1, Amount amount2)

            throws CurrenciesDoNotMatchException {

        if (!amount1.currency.equals(amount2.currency)) {

            throw new CurrenciesDoNotMatchException();

        }

        return new Amount(amount1.currency, amount1.amount + amount2.amount);

    }

}

How should the Exception catch blocks be ordered ?


Specific Exception catch blocks should be before the catch block for a Generic Exception. For example, CurrenciesDoNotMatchException should be before Exception. Below code gives a compilation error.

    public static void main(String[] args) {

        try {

            AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("DOLLAR",

                    5));

        } catch (Exception e) { // COMPILER ERROR!!

            System.out.println("Handled Exception");

        } catch (CurrenciesDoNotMatchException e) {

            System.out.println("Handled CurrenciesDoNotMatchException");

        }

    }

What are the new features related to Exception Handling introduced in Java7?


Automatic resource management. JVM takes care of closing the connection when we use try with resources.

  try (FileInputStream input = new FileInputStream("file.txt")) {

   int data = input.read();

   while (data != -1) {

    System.out.print((char) data);

    data = input.read();

   }

  }

 

Multiple Repeated Exception Blocks not needed anymore. We can use a single exception block to catch multiple exception types.

catch (IOException|SQLException ex) {

    logger.log(ex);

    throw ex;

}

Can you explain some Exception Handling Best Practices?


Never Completely Hide Exceptions. At the least log them. printStactTrace method prints the entire stack trace when an exception occurs. If you handle an exception, it is always a good practice to log the trace.


     public static void main(String[] args) {

        try {

            AmountAdder.addAmounts(new Amount("RUPEE", 5), new Amount("RUPEE",

                    5));

            String string = null;

            string.toString();

        } catch (CurrenciesDoNotMatchException e) {

            System.out.println("Handled CurrenciesDoNotMatchException");

            e.printStackTrace();

        }

    }


Best practices you follow while doing Exception handling in Java ?




There are lot of best practices, which can help to make your code robust and flexible at same time, here are few of

them:




1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since

NullPointerException is most infamous of all Java exceptions, there are lot of techniques andcoding best practices to minimize NullPointerException. You can check that link for some specific examples.




2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in Exception handling because they just

ate Exception without any clue, at bare minimum print stack trace but you should do alternative operation which make sense or defined by requirements.




3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it

improves readability of code by removing boiler plate exception handling code




4) Never let your database Exception flowing till client error. since most of application deal

with database and SQLException is a checked Exception in Java you should consider handling any database related

errors in DAO layer of your application and only returning alternative value or

something meaningfulRuntimeException which client can understand and take action.




5) calling close() methods for connections, statements, and streams on finally block in

Java.

Sunday, 19 March 2017

OOPS Benefits

It simplifies the software development and maintenance by providing some concepts:
  • Object.
  • Class.
  • Inheritance.
  • Polymorphism.
  • Abstraction.
  • Encapsulation.

Benefits of the Java Collections Framework

 OOP offers several benefits to the program designer and the user. Object-orientation contributes to the solutions of many problem associated with the development and quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. The principal advantages are:

·        Through inheritance, we can eliminate redundant code and extend the use of existing classes.
·        We can built programs from standard working modules that communicate with one another rather than, having to start writing the code from scratch. This leads to saving of development time and higher productivity.
·        The principle of data hiding helps the programmers to built secure program that can’t be invaded by code in other parts of the program.
·        It is possible to have multiple objects to coexist without any interference.
·        It is possible to map objects in the problem domain to those objects in the program.
·        It is easy to partition the work in a project based on objects.
·        The data-centered design approach enables us to capture more details of the model in an implementable form.
·        Object-oriented systems can be easily upgraded from small to large system
·        Message passing technique for communication between objects make the interface descriptions with external system much simpler.
·        Software complexity can be easily managed.

Object Oriented Concept Part 2

Object Oriented Programming

OOPs concepts, Object Class and instance
Object
Object:  is a bundle of related variables and functions (also known methods).
Objects share two characteristics: They have State and Behavior.
State: State is a well defined condition of an item. A state captures the relevant aspects of an object
Behavior: Behavior is the observable effects of an operation or event,
Examples:
eg 1:
Object: House
State: Current Location, Color, Area of House etc
Behavior: Close/Open main door.
eg 2:
Object: – Car
State: Color, Make
Behavior: Climb Uphill, Accelerate, SlowDown etc
Note: Everything a software object knows (State) and can do (Behavior) is represented by variables and methods (functions) in the object respectively.
Characteristics of Objects:
  1. Abstraction
  2. Encapsulation
  3. Message passing

Message passing

A single object by itself may not be very useful. An application contains many objects. One object interacts with another object by invoking methods (or functions) on that object. Through the interaction of objects, programmers achieve a higher order of functionality which has complex behavior.
One object invoking methods on another object is known as Message passing.
It is also referred to as Method Invocation.
OOPs concepts, Message passing

Class

A class is a prototype that defines the variables and the methods common to all objects of a certain kind. Member Functions operate upon the member variables of the class. An Object is created when a class in instantiated.
How to create an Object?
An object is created when a class is instantiated
Declaring an Object of class :
ClassName Objectname;
Object definition is done by calling the class constructor
Constructor: A special member function which will be called automatically to initialize the data member of a class whenever object is instantiated.
Memory space is allocated only when a class is instantiated i.e. when an object is created
Defining a variable :
E.g. GraduationCourse mycourse= new GraduationCourse();
Object Oriented Programming features:
Object-oriented-programming-features

Abstraction

The purpose of abstraction is to hide information that is not relevant or rather show only relevant information and to simplify it by comparing it to something similar in the real world.
Abstraction means “The process of forming of general and relevant concept from more complex scenarios”. 
Note 1: Abstraction is used to build complex systems.
Key to simplify a complex design into smaller, manageable parts which then become the components of a bigger and complex system.
The idea of hiding the complexity within a smaller/simple component of a system.
Note 2: Abstraction is not a feature of Object oriented concepts alone. Even in procedural language programming, abstraction can be achieved to a limited extent by hiding complex internals through well formed business logic and functions.

Encapsulation

Encapsulation means the localization of the information or knowledge within an object.
Encapsulation is also called as “Information Hiding”.
1) Objects encapsulate data and implementation details. To the outside world, an object is a black box that exhibits a certain behavior.
2) The behavior of this object is what which is useful for the external world or other objects.
3) An object exposes its behavior by means of methods or functions.
4) The set of functions an object exposes to other objects or external world acts as the interface of the object.
Benefits of Encapsulation
1) The functionality where in we can change the implementation code without breaking the code of others who use our code is the biggest benefit of Encapsulation.
2) Here in encapsulation we hide the implementation details behind a public programming interface. By interface, we mean the set of accessible methods our code makes available for other code to call—in other words, our code’s API.
3) By hiding implementation details, We can rework on our method code at a later point of time, each time we change out implementation this should not affect the code which has a reference to our code, as our API still remains the same
How to bring in Encapsulation
1) Make the instance variables protected.
2) Create public accessor methods and use these methods from within the calling code.
3) Use the JavaBeans naming convention of getter and setter.
Eg: getPropertyNamesetPropertyName.
Example for encapsulation
class EmployeeCount
{
   private int NoOfEmployees = 0;
   public void setNoOfEmployees (int count)
   {
       NoOfEmployees = count;
   }
   public double getNoOfEmployees () 
   {
       return NoOfEmployees;
   }
}
class Encapsulation
{
   public static void main(String args[])
   {
      System.out.println("Starting EmployeeCount...");
      EmployeeCount employeeCount = new EmployeeCount ();
      employeeCount. setNoOfEmployees (12003);
      System.out.println("NoOfEmployees = " + employeeCount. getNoOfEmployees ());
    }
}
Takeaway from above example:
The application using an Object of this class EmployeeCount will not able to get the NoOfEmployees directly.
Setting and getting the value of the field NoOfEmployees is done with the help of Getter and setter method as shown below.

Inheritance

The process by which one class acquires the properties and functionalities of another class. Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it.
  1. Inheritance is a mechanism of defining a new class based on an existing class.
  2. Inheritance enables reuse of code. Inheritance also provides scope for refinement of the existing class. Inheritance helps in specialization
  3. The existing (or original) class is called the base class or super class or parent class. The new class which inherits from the base class is called the derived class or sub class or child class.
  4. Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.
Note : The biggest advantage of Inheritance is that, code in base class need not be rewritten in the derived class.
The member variables and methods of the base class can be used in the derived class as well.
Inheritance Example
Consider below two classes –
Class Teacher:
class Teacher {
   private String name;
   private double salary;
   private String subject;
   public Teacher (String tname)  {
       name = tname;
   }
   public String getName()  {
       return name;
   }
   private double getSalary()  {
       return salary;
   }
   private String  getSubject()  {
        return  subject;
   }
}
Class: OfficeStaff
class  OfficeStaff{
   private String name;
   private double salary;
   private String dept;
   public OfficeStaff (String sname)  {
      name = sname;
   }
   public String getName()  {
       return name;
   }
   private double  getSalary()  {
       return salary;
   }
   private String  getDept ()  {
       return dept;
   }
}
Points:
1) Both the classes share few common properties and methods. Thus repetition of code.
2) Creating a class which contains the common methods and properties.
3) The classes Teacher and OfficeStaff can inherit the all the common properties and methods from below Employee class
class Employee{
   private String name;
   private double salary;
   public Employee(String ename){
      name=ename;
   }
   public String getName(){
      return name;
   }
   private double getSalary(){
      return salary;
   } 
}
4) Add individual methods and properties to it Once we have created a super class that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses
5) Any similar classes like Engineer, Principal can be generated as subclasses from the Employee class.
6) The parent class is termed super class and the inherited class is the sub class
7) A sub class is the specialized version of a super class – It inherits all of the instance variables and methods defined by the super class and adds its own, unique elements.
8) Although a sub class includes all of the members of its super class it can not access those members of the super class that have been declared as private.
9) A reference variable of a super class can be assigned to a reference to any sub class derived from that super class
i.e. Employee emp = new Teacher();
Note: Multi-level inheritance is allowed in Java but not multiple inheritance
multilevel and multiple inheritance diagram representation, Object oriented programming concepts
Types of Inheritance
Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class.
Multiple Inheritance
Multiple Inheritance” refers to the concept of one class inheriting from more than one base class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple inheritance” is that the derived class will have to manage the dependency on two base classes.
Note 1Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often leads to problems in the hierarchy. This results in unwanted complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple Inheritance is supported in C++.

Polymorphism

Polymorphism is a feature that allows one interface to be used for a general class of actions. It’s an operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface. Polymorphism is extensively used in implementing inheritance.
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Function Overloading – within same class more than one method having same name but differing in signature.
Resolved during compilation time.
Return type is not part of method signature.
Dynamic Polymorphism
Function Overriding – keeping the signature and return type same, method in the base class is redefined in the derived class.
Resolved during run time.
Which method to be invoked is decided by the object that the reference points to and not by the type of the reference.
Overriding:
Redefining a super class method in a sub class is called method overriding.
The method signature ie. method name, parameter list and return type have to match exactly.
The overridden method can widen the accessibility but not narrow it, ie if it is private in the base class, the child class can make it public but not vice versa.
Overriding Examples:
Consider a Super Class Doctor and Subclass Surgeon. Class Doctor has a method treatPatient(). Surgeon overrides treatPatient method ie gives a new definition to the method.
Doctor doctorObj = new Doctor();
// Call the treatPatient method of Doctor class
doctorObj.treatPatient() 
Surgeon surgeonObj = new Surgeon();
// Call the treatPatient method of Surgeon class
surgeonObj.treatPatient()
Doctor obj = new Surgeon();
// calls Surgeon’s treatPatient method as the reference is pointing to Surgeon
obj.treatPatient();
Method/Function Overloading:
Method Overloading refers to the practice of using the same name to denote several different operations. Overloading can be done for both functions as well as operators. Here we look at only Method overloading.
Declaration:
void SomeMethod (int value);
void SomeMethod (float value);
void SomeMethod (char value);
void SomeMethod (String* str);
void SomeMethod (char* str);
All the five methods are called ‘SomeMethod ’. All the methods have the same name, but different signatures.
The concept of the same function name with different types of parameters being passed is called Function Overloading.
1) In Overloading we can reuse the same method name by changing the arguments.
2) Overloaded methods- Must and Must Not Facts:
  • The Overloaded method must have different argument lists,
  • Can have different return types but in that case it is mandatory to have different argument list.
  • Can have different access modifiers and
  • Can throw different exceptions
3) Methods can be overloaded in the same as well as the sub classes.
Q: What determines which overridden method is used at runtime?
A: Object type
Q: What determines which overloaded method will be used at compile time?
A: Reference type determines. Operator overloading refers to the operators like ‘+’ being used for different purposes based on the data type on either side of the operator.

Combined example for Inheritance & Polymorphism

abstract public class Employee {
   private String name;
   public Employee(String ename) { 
      name = ename;
   }
   public String getName() {
      return new name;
   }
   private void setName(String name) {
      this.name = new String(name);
   }
   abstract public double pay();
   public String toString() {
       return "name is" + name;
   }
}
public class Salaried extends Employee {
   double salary;
   public Salaried(String name, double s) {
      super(name);
      salary =s;
   }
   public void setSalary(double salary) {
      this.salary = salary;
   }
   public double getSalary() {
      return salary;
   }
   public double pay() {
      return salary;
   }
   public String toString(){
      return super.toString() + " (salary is " +salary+")"; 
   }
}

IS-A & HAS-A Relationships

public class SuperClass {  }
public class SubClass1 extends SuperClass { //SubClass 1 code goes here }
public class SubClass2 extends SubClass1 { //SubClass2 Specific code goes here }
HAS-A relationships are based on usage, rather than inheritance. In other words, class A HAS-A B if code in class A has a reference to an instance of class B.
For example, we can say the following,
A Car IS-A Vehicle. A Car HAS-A License. and the code looks like this:
public class Vehicle{ }
public class Car extends Vehicle{
   private License myCarLicense;
}

Interfaces

As in the above example Teacher class contains the attributes and methods of Employee as well as Musician.
  1. Java does not support Multiple Inheritance
  2. Interface is similar to an abstract class that contains only abstract methods
  3. Declared with the keyword interface instead of the keyword class
  4. Keyword implements is used to represent the interfaces implemented by the class
Interface: Syntax
class ClassName extends Superclass implements Interface1, Interface2, ....
Example : class MusicTeacher extends Teacher implements Musician
Java OOps, Interface example diagram
All methods in an interface are implicitly public and abstract.
The keyword abstract before each method is optional.
An interface may contain definitions of final variables.
A class may extend only one other class, but it may implement any number of interfaces.
When a class implements an interface, it may implement (define) some or all of the inherited abstract methods.
A class must itself be declared abstract if it inherits abstract methods that it does not define.
An interface reference can point to objects of its implementing classes.
Abstract method
1) A method that is declared but not defined
2) Declared with the keyword abstract
3) Example :
abstract public void playInstrument();
4) Has a header like any other method, but ends with a semicolon instead of a method body
5) Used to put some kind of compulsion on the class who inherits from this class. i.e., the class who inherits MUST provide the implementation of the method else the subclass will also become abstract
6) The following cannot be marked with “abstract” modifier
  • Constructors
  • Static methods
  • Private methods
  • Methods marked with “final” modifier

Abstract Classes

Abstract Classes
Outlines the behavior but not necessarily implements all of its behavior. Also known as Abstract Base Class.
Provides outline for behavior by means of method (abstract methods) signatures without an implementation.
Note 1: There can be some scenarios where it is difficult to implement all the methods in the base class. In such scenarios one can define the base class as an abstract class which signifies that this base class is a special kind of class which is not complete on its own.
A class derived from the abstract base class must implement those member functions which are not implemented in the abstract class.
Note 2: Abstract Class cannot be instantiated.
To use an abstract class one has to first derive another class from this abstract class using inheritance and then provide the implementation for the abstract methods.
Note 3: If a derived class does not implement all the abstract methods (unimplemented methods), then the derived class is also abstract in nature and cannot be instantiated.
Example of Abstract class and Abstract Method:
abstract class Costume {
  abstract public void Stitch();
   public void  setColour (){
     //code to set colour
   }
}
Here the class which inherits abstract class Costume can implement the abstract method Stitch depending upon what kind of Costume it is.

What is a Constructor

1) A method with the same name as class name used for the purpose of creating an object in a valid state
2) It does not return a value not even void
3) It may or may not have parameters (arguments)
4) A class contains one or more constructors for making new objects of that class
5) If (and only if) the programmer does not write a constructor, Java provides a default constructor with no arguments.
The default constructor sets instance variables as:
  • numeric types are set to zero
  • boolean variables are set to false
  • char variables are set to ‘’
  • object variables are set to null.
When a constructor executes, before executing its own code:
It implicitly call the default constructor of it’s super class Or can make this constructor call explicitly, with super(…);
A constructor for a class can call another constructor for the same class by putting this(…); as the first thing in the constructor. This allows you to avoid repeating code.
A Class do not inherit the constructors of a super class.
Generalization and Specialization:
In order to implement the concept of inheritance in an OO solution, one has to first identify the similarities among different classes so as to come up with the base class.
This process of identifying the similarities among different classes is called Generalization.
The class which is identified after generalization is the base class. The classes over which the generalization is made are the derived classes.
The classes over which the generalization is built are viewed as Specialization.
Generalization identifies the common attributes and behavior among different entities whereas specialization identifies the distinct attributes and their behavior which differentiate a derived class from the other classes.
Generalization–Specialization hierarchy is used to depict the relationship between the generalized class and the corresponding specialized classes.

Access Specifiers

Access specifiers in a class
An access specifier is a keyword in OO Programming languages, which specify what access is permitted on a member.
There are three types of access specifiers:
public: Accessible to all. Other objects can also access this member variable or function.
private: Not accessible by other objects. Private members can be accessed only by the methods in the same class. Object accessible only in Class in which they are declared.
protected: The scope of a protected variable is within the class which declares it and in the class which inherits from the class (Scope is Class and subclass)
Default: Scope is Package Level
Approach to Object Oriented Design:
Step 1. Identify all the classes (Nouns; Type of objects) in the requirement specification,
Step 2. Identify the commonalities between all or small groups of classes identified (generalization) if it is obvious. Do not force fit generalization where it doesn’t make sense.
Step 3. In any given situation, start with the simplest object which can be abstracted into individual classes
Step 4. Identify all the member variables and methods the class should have
Step 5. Ensure that the class is fully independent of other classes and contains all the attributes and methods necessary.
Step 6. Keep all the data members private or protected
Step 7. The methods in the class should completely abstract the functionality
Step 8. The methods in the class should not be a force fit of procedural code into a class
Step 9. Inherit and extend classes from the base classes ONLY IF the situation has scope for it
Step 10. Define the relationships among the classes (“Has-A”, “Uses-A”)
Step 11. Keep the number of classes in your application under check (do not create any unnecessary classes)