Friday, March 10, 2017

Inheritance in Java

The process of obtaining the data members and methods from one class to another class is known as inheritance. It is one of the fundamental features of object-oriented programming.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Let us see how extend keyword is used to achieve Inheritance.

class Vehicle
{
  …… 
}
class Car extends Vehicle
{
 …….   //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,
• Vehicle is super class of Car.
• Car is sub class of Vehicle.
• Car IS-A Vehicle.

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

Simple example of Inheritance

class Parent
{
   public void p1()
   {
        System.out.println(“Parent method”);
   }
}
public class Child extends Parent 
{
  public void c1()
   {
        System.out.println(“Child method”);
   }
public static void main(String[] args)
  {
       Child cobj = new Child();
       cobj.c1(); //method of Child class
       cobj.p1(); //method of Parent class 
  }
}
Output :
Child method
Parent method

Types of Inheritance

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
NOTE*: Multiple inheritance is not supported in java.Inheritance Content -1

Q. Why multiple inheritance is not supported in Java

• To remove ambiguity.
• To provide more maintainable and clear design.
Inheritance Content -2

Q. What is not possible using java class Inheritance?

1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass

Abstraction in Java






Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don’t know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class:

If a class contain any abstract method then the class is declared as abstract class. An abstract class is never instantiated. It is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method.
Syntax :
abstract class class_name { }

Abstract method:

Method that are declared without any body within an abstract class are called abstract method. The method body will be defined by its subclass. Abstract method can never be final and static. Any class that extends an abstract class must implement all the abstract methods declared by the super class.
Syntax :
abstract return_type function_name ();    // No definition
Example of abstract class that has abstract method-
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
abstract class Bike

     abstract void run(); 

class Honda4 extends Bike

     void run()
   {
     System.out.println(“running safely..”);
   } 
public static void main(String args[])
   { 
     Bike obj = new Honda4(); 
     obj.run(); 
   } 

Output:
running safely..

Q. When to use Abstract Methods & Abstract Class?

Abstract methods are usually declared where two or more subclasses are expected to do a similar thing in different ways through different implementations. These subclasses extend the same Abstract class and provide different implementations for the abstract methods.
Abstract classes are used to define generic types of behaviors at the top of an object-oriented programming class hierarchy, and use its subclasses to provide implementation details of the abstract class.

Important Points about Abstract classes and methods:

  1. abstract keyword is used to create an abstract class in java.
  2. Abstract class in java can’t be instantiated.
  3. We can useabstract keyword to create an abstract method, an abstract method doesn’t have body.
  4. If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
  5. It’s not necessary to have abstract class to have abstract method.
  6. If abstract class doesn’t have any method implementation, it’s better to use interface because java doesn’t support multiple class inheritance.
  7. The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.
  8. All the methods in an interface are implicitly abstract unless the interface methods are static or default. Static methods and default methods in interfaces are added in Java 8
  9. Java Abstract class can implement interfaces without even providing the implementation of interface methods.
  10. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.
  11. We can run abstract class in java like any other class if it has main()

Thursday, March 9, 2017

Constructors in Java


   
A constructor is a special method that is used to initialize an object. Every class has a constructor, if we don’t explicitly declare a constructor for any java class the compiler builds a default constructor for that class.

* Rules for create a Java Constructor

  • A constructor does not have any return type.
  • A constructor has same name as the class in which it resides.
  • Constructor in Java cannot be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

Types of java constructors- 

There are two types of constructors:
  1. Default constructor (no-arg constructor)
2. Parameterized constructor
Each time a new object is created at least one constructor will be invoked.
Car c = new Car()        //Default constructor invoked
Car c = new Car(name);       //Parameterized constructor invoked

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc. depending on the type.

Constructor Overloading

Constructors in Java may be overloaded. This means that a class can have MORE than one constructor. This is useful for when you want the object to be created with different parameters up front. There are two ways a Java constructor can be overwritten: give the new constructor a different number of parameters, or give the new constructor at least one different type of parameter.
Example of constructor overloading
class Cricketer
{
 String name;
 String team;
 int age;
 Cricketer ()      //default constructor.
    {
        name =””;
        team =””;
        age = 0;
    }
 Cricketer(String n, String t, int a)         //constructor overloaded
    {
       name = n;
       team = t;
       age = a;
    }
 Cricketer (Cricketer ckt)     //constructor similar to copy constructor of c++
    {
       name = ckt.name;
       team = ckt.team;
       age = ckt.age;
    }
 public String toString()
   {
       return “this is ” + name + ” of “+team;
    }
}
Class test:
{
 public static void main (String[] args)
    {
       Cricketer c1 = new Cricketer();
       Cricketer c2 = new Cricketer(“sachin”, “India”, 32);
       Cricketer c3 = new Cricketer(c2 );
       System.out.println(c2);
       System.out.println(c3);
        c1.name = “Virat”;
        c1.team= “India”;
        c1.age = 32;
        System .out. print in (c1);
    }
}
output:
this is sachin of india
this is sachin of india
this is virat of india

Important points to be remember about Construction :-

  1. Every class has a constructor whether it’s normal one or a abstract class.
  2. As stated above, constructor are not methods and they don’t have any return type.
  3. Constructor name and class name should be the same.
  4. Constructor can use any access specifier; they can be declared as private also. Private constructors are possible in java but their scope is within the class only.
  5. Constructor gets called automatically after creation of object and before completion of new Operator
  6. Like constructor’s method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.
  7. If you don’t define any constructor within the class, compiler will do it for you and it will create a constructor for you.
  8. this() and super() should be the first statement in the constructor code.If you don’t mention them, compiler does it for you accordingly.
  9. Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.
  10. Constructors can not be inherited.
  11. If Super class doesn’t have a no-arg(default) constructor then compiler would not define a default one in child class as it does in normal scenario.
  12. Interfaces do not have constructors.
  13. Abstract can have constructors and these will get invoked when a class, which implements interface, gets instantiated. (i.e. object creation of concrete class).
  14. A constructor can also invoke another constructor of the same class – By using this(). If you wanna invoke a arg-constructor then give something like: this(parameter list).

Difference between Constructor and Method 
Constructor
Method
The purpose of constructor is to create object of a classThe purpose of a method is to perform a task by executing java code.
Constructors cannot be abstract, final, static and synchronisedMethods can be abstract, final, static and synchronised
Constructors do not have return typesMethods have return types
The java compiler provides a default constructor if you don’t have any constructor.Method is not provided by compiler in any case.

Wednesday, March 8, 2017

Method Overloading Vs Method Overriding

Method overloading

If two or more method in a class has same name but different parameters, it is known as method overloading.
Method overloading is one of the ways through which java supports polymorphism. Method overloading can be done by changing the number of arguments or by changing the data type of arguments. If two or more method has same name and same parameter list but differs in return type are not said to be overloaded method.

Different ways of Method overloading:

There are two different ways of method overloading

1. Method overloading by changing data type of Arguments

Example:
class Calculate
{
      void sum (int a, int b)
    {
          System.out.println(“sum is”+(a+b)) ;
    }
     void sum (float a, float b)
   {
         System.out.println(“sum is”+(a+b));
    }
Public static void main (String[] args)
     {
         Calculate cal = new Calculate();
         cal.sum (8,5); //sum(int a, int b) is method is called. 
         cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
     }
}
Output :
Sum is 13
Sum is 8.4
You can see that sum() method is overloaded two times. The first takes two integer arguments, the second takes two float arguments.

2. Method overloading by changing no. of argument.

Example :
class Area
{
       void find(int l, int b)
   {
        System.out.println(“Area is”+(l*b)) ;
   }
     void find(int l, int b,int h)
  {
       System.out.println(“Area is”+(l*b*h));
  }
public static void main (String[] args)
   {
       Area ar = new Area();
       ar.find(8,5);       //find(int l, int b) is method is called. 
       ar.find(4,6,2);   //find(int l, int b,int h) is called.
    }
}
Output :
Area is 40
Area is 48
In this example the find() method is overloaded twice. The first takes two arguments to calculate area, and the second takes three arguments to calculate area.

Method Overriding

When a method in a sub class has the same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the ability to define the method that’s specific to a particular subclass type.

Example of Method Overriding

class Animal
{
    public void eat()
  {
        System.out.println(“Generic Animal eating”);
   }
}
class Dog extends Animal
{
      public void eat()   //eat() method overriden by Dog class.
   {
         System.out.println(“Dog eat meat”);
    }
}
As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature.
NOTE*: Static methods cannot be overridden because a static method is bounded with the class whereas instance method is bounded with an object.

Difference between Overloading and Overriding-

Method overloading

Method Overriding

Parameter must be different and name must be same.Both name and parameter must be same.
Compile time polymorphism.Run time polymorphism.
Increase readability of code.Increase reusability of code.
Access specifier can be changed.Access specifier most not be more restrictive than original method(can be less restrictive).
Method overloading is performed within the class.Method overriding occurs in two classes that have IS-A (inheritance) relationship.