Tuesday, July 16, 2013

Core Java OOPS concepts


Abstraction


You can’t instantiate an abstract class. However, you can create a subclass that extends an abstract class and provides an implementation of the abstract methods defined by the abstract class. You can instantiate the subclass. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete sub-classes down the inheritance tree.

 An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract. 

When you subclass an abstract class, the subclass must provide an implementation for each abstract method in the abstract class. In other words, it must override each abstract method.

Abstract classes are useful when you want to create a generic type that is used as the super class for two or more sub-classes,
A Java constructor is implicitly final and implicitly static, and it is meaningless for a Java constructor to be abstract.

I have created a best example called Shape.


Let’s consider Shape is either Line or Curve or Circle … I want to draw the shape for all these three types. So, first create a abstract class called Shape and place a abstract method called draw(). Create there different classes for these three types of sub classes which extends Shape class. Now you cannot instantiate super class (Shape) but you can instantiate subclass using the key word new.
       
     EX:  Shape lineShape = new Line();
            Shape curveShape = new Curve();


Here are a few additional details regarding abstract classes:


            ü  Not all the methods in an abstract class have to be abstract. A class can provide an implementation for some of its methods but not others. In fact, even if a class doesn't have any abstract methods, you can still declare it as abstract. (In that case, though, the class can’t be instantiated).
    ü  A private method can’t be abstract. All abstract methods must be public.
    ü  A class can’t be both abstract and final.
    ü  Interfaces are by default abstract and only contains public static, final constant or abstract methods.






Polymorphism




Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. 

Java supports different kinds of polymorphism like overloading, overriding, parametric etc.



     EX:
          public interface Vegetarian{}
          public class Animal{}

          public class Deer extends Animal implements Vegetarian{}

Now the Deer class is considered to be polymorphic since this has multiple inheritances. Following are true for the above example:

      
      ü  A Deer IS-A Animal
      ü  A Deer IS-A Vegetarian
      ü  A Deer IS-A Deer
      ü  A Deer IS-A Object


When we apply the reference variable facts to a Deer object reference, the following declarations are legal:


Overloading


Same method name with different arguments in a class is called method overloading. Based on the number and type of arguments we provide while calling the method, the correct method will be called.

Overloaded methods:


      ü  appear in the same class or a subclass
   ü  have the same name but,
     ü  have different parameter lists, and,
   ü  can have different return types

Constructor Overloading:



    ü  Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.  
   ü  The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.


Overriding



         Overriding is defining a method in a subclass with the same name and type signature as a method in its super class and when this subclass instance appears in the super class context like Parent p = new Child() and when we execute an overridden method as p.myMethod(), the subtype’s version of that method is executed. Here, the actual method called will depend on the object at run time, not the reference type.


    Ø  Overriding method cannot throw higher Exception than original or overridden method. Means if original method throws IOException than overriding method cannot throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
    Ø  Overriding method cannot reduce accessibility of overridden method, means if original or overridden method is public than overriding method cannot make it protected.
    Ø   From Java5 onwards you can use annotation in Java to declare overridden method just like we did with @override. @override annotation allows compiler, IDE like NetBeans and Eclipse to cross verify or check if this method is really overrides super class method or not.
    Ø From Java 5, you're allowed to change the return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden (super class) method.



     ü  overriding method MUST have the same argument list (if not, it might be a case of overloading)
     ü  overriding method MUST have the same return type; the exception is covariant return (used as of Java 5) which returns a type that is a subclass of what is returned by the overridden method
     ü  abstract methods MUST be overridden
     ü  final methods CANNOT be overridden
     ü  static methods CANNOT be overridden
     ü  constructors CANNOT be overridden



Difference between method overloading vs overriding in Java


       ü   First and most important difference between method overloading and overriding is that, In case of method overloading in Java, Signature of method changes while in case of method overriding it remain same.
      ü  Second major difference between method overloading vs overriding in Java is that you can overload method in one class but overriding can only be done on subclass.
      ü  You cannot override staticfinal and private method in Java but you can overload static, final or private method in Java.
      ü  Overloaded method in Java is bonded by static binding (Compile time) and overridden methods are subject to dynamic binding (Run-time).
      ü  Private and final method can also be not overridden in Java.


Encapsulation



Encapsulation is the concept of hiding the implementation details of a class and allowing access to the class through a public interface. For this, we need to declare the instance variables of the class as private or protected. 

The client code should access only the public methods rather than accessing the data directly. Also, the methods should follow the Java Bean's naming convention of set and get.
 

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.


public class Employee 
{
 
private float salary;
 
public float getSalary()
 
{
 
return salary;
 
}
 
public void setSalary(float salary)
 
{
 
this.salary = salary;
 
}


Advantage of Encapsulation


Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:
  • Encapsulated Code is more flexible and easy to change with new requirements.
  • Encapsulation in Java makes unit testing easy.
  • Encapsulation in Java allows you to control who can access what.
  • Encapsulation also helps to write immutable class in Java which are a good choice in multi-threading
  • Environment.
  • Encapsulation reduce coupling of modules and increase cohesion inside a module because all piece of one thing
  • are encapsulated in one place.
  • Encapsulation allows you to change one part of code without affecting other part of code.

What should you encapsulate in code?

Anything which can be change and more likely to change in near future is candidate of Encapsulation. This also helps to write more specific and cohesive code. Example of this is object creation code, code which can be improved in future like sorting and searching logic.

Inheritance




A class can acquire the characteristics of another class. I.e. it’s a method of creating a new class based on already existing class.
The class from which its inheriting is called base class  and the class which is inheriting is called sub class. Java does not support Multiple Inheritance.
A subclass inherits all the members (fields, methods, and nested classes) from its super class. Constructors are not members, so they are not inherited by subclasses, but the constructor of the super class can be invoked from the subclass.

The following kinds of inheritance are there in java.
  • Ø  Simple Inheritance
  • Ø  Multilevel Inheritance

Simple Inheritance



When a subclass is derived simply from it’s parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it’s parent class. It is also called single inheritance or one level inheritance.


Class BaseClass{
}
Class Subclass extends BaseClass{
}


Multilevel Inheritance


It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it’s parent class and this parent class works as the child class for it’s just above ( parent ) class.  Multilevel inheritance can go up to any number of level.
Along with the above example we can also add the below code.

Class SubSubClass extends SubClass{
}
  • IS-A,HAS-A relationship:
  • IS-A refers to inheritance or implementation.
  • IS-A is expressed with the keyword extends.
  • HAS-A means instance of one class “has a” reference to an instance of another class or another instance of the same class.


Example:


  • Car is a vehicle
  • Vechile has a engine
  • Car has a engine


Note:


  • Private members of super class is not accessible in subclass,
  • Super class is also called parent class or base class,
  • Subclass is also called child class or derived class.


What You Can Do in a Subclass



A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members:


  • The inherited fields can be used directly, just like any other fields.
  •  You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it (not recommended).
  • You can declare new fields in the subclass that are not in the superclass.
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can declare new methods in the subclass that are not in the superclass.
  • You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super.

Private Members in a Superclass



A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.
A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

No comments:

Post a Comment