Wednesday, 2 March 2016

Java Fundamentals -3

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 is known as 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

abstract class A
{
 abstract void callme(); 
}
class B extends A
{
 void callme()
 {
  System.out.println("this is callme."); 
 }
 public static void main(String[] args)
 {
  B b=new B();
  b.callme();
 }
}
output: this is callme.

Abstract class with concrete(normal) method.

Abstract classes can also have normal methods with definitions, along with abstract methods.
abstract class A
{
 abstract void callme();
 public void normal()
 {
  System.out.println("this is concrete method");
 }  
}
class B extends A
{
 void callme()
 {
  System.out.println("this is callme."); 
 }
 public static void main(String[] args)
 {
  B b=new B();
  b.callme();
  b.normal();
 }
}
output: 
this is callme.
this is concrete method.

Points to Remember

  1. Abstract classes are not Interfaces. They are different, we will study this when we will study Interfaces.
  2. An abstract class must have an abstract method.
  3. Abstract classes can have Constructors, Member variables and Normal methods.
  4. Abstract classes are never instantiated.
  5. When you extend Abstract class with abstract method, you must define the abstract method in the child class, or make the child class abstract.

Abstraction using abstract class

Abstraction is an important feature of OOPS. It means hiding complexity. Abstract class is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method. Lets see how abstract class is used to provide abstraction.
abstract class Vehicle
{
   public abstract void engine();  
}
public class Car extends Vehicle {
    
    public void engine()
    {
        System.out.println("Car engine");
        //car engine implementation
    }
    
    public static void main(String[] args)
    {
        Vehicle v = new Car();
        v.engine();
        
    }
}
Output
Car engine
Here by casting instance of Car type to Vehicle reference, we are hiding the complexity of Car type under Vechicle. Now the Vehicle reference can be used to provide the implementation but it will hide the actual implementation process.

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.

Interface

Interface is a pure abstract class.They are syntactically similar to classes, but you cannot create instance of an Interface and their methods are declared without any body. Interface is used to achieve complete abstraction in Java. When you create an interface it defines what a class can do without saying anything about how the class will do it.
Syntax :
interface interface_name { }

Example of Interface

interface Moveable 
{ 
 int AVERAGE-SPEED=40;
 void move();
}
Interface in Java
NOTE : Compiler automatically converts methods of Interface as public and abstract, and the data members as public, static and final by default.

Rules for using Interface

  • Methods inside Interface must not be static, final, native or strictfp.
  • All variables declared inside interface are implicitly public static final variables(constants).
  • All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword.
  • Interface can extend one or more other interface.
  • Interface cannot implement a class.
  • Interface can be nested inside another interface.

Example of Interface implementation

interface Moveable 
{
 int AVG-SPEED = 40;
 void move();
}

class Vehicle implements Moveable 
{
 public void move()
 {
  System .out. print in ("Average speed is"+AVG-SPEED");
 }
 public static void main (String[] arg)
 {
  Vehicle vc = new Vehicle();
  vc.move();
 }
}
Output:
Average speed is 40.

Interfaces supports Multiple Inheritance

Though classes in java doesn't suppost multiple inheritance, but a class can implement more than one interface.
interface Moveable 
{
 boolean isMoveable();
}

interface Rollable
{
 boolean isRollable
}

class Tyre implements Moveable, Rollable 
{
 int width;

 boolean isMoveable()
 {
  return true;
 }

 boolean isRollable()
 {
  return true;
 }
 public static void main(String args[])
 {
  Tyre tr=new Tyre();
  System.out.println(tr.isMoveable());
  System.out.println(tr.isRollable());
 }
}
Output:
true
true

Interface extends other Interface

Classes implements interfaces, but an interface extends other interface.
interface NewsPaper
{
 news();
}

interface Magazine extends NewsPaper
{
 colorful();
} 

Inheritance (IS-A)

Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java.
Inheritance in Java
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.

Purpose of Inheritance

  1. To promote code reuse.
  2. To use Polymorphism.

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

Another example of Inheritance

class Vehicle
{
    String vehicleType;
}
public class Car extends Vehicle {
    
    String modelType;
    public void showDetail()
    {
        vehicleType = "Car";        //accessing Vehicle class member
        modelType = "sports";
        System.out.println(modelType+" "+vehicleType);
    }
    public static void main(String[] args)
    {
        Car car =new Car();
        car.showDetail();
    }
}
Output
sports Car

Types of Inheritance

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
Types of Inheritance in Java

Why multiple inheritance is not supported in Java

  • To remove ambiguity.
  • To provide more maintainable and clear design.
problem with multiple inheritance

super keyword

In Java, super keyword is used to refer to immediate parent class of a class. In other words super keyword is used by a subclass whenever it need to refer to its immediate super class.
example of super keyword in java

Example of Child class refering Parent class property using super keyword

class Parent
{
    String name;
    
}
public class Child extends Parent {
    String name;
    public void details()
    {
        super.name = "Parent";     //refers to parent class member
        name = "Child";
        System.out.println(super.name+" and "+name);
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.details();
    }
}
Output
Parent and Child

Example of Child class refering Parent class methods using super keyword

class Parent
{
    String name;
    public void details()
    {
      name = "Parent";
        System.out.println(name);
    }  
}
public class Child extends Parent {
    String name;
    public void details()
    {
        super.details(); //calling Parent class details() method
        name = "Child";
        System.out.println(name);
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.details();
    }
}
Output
Parent
Child

Example of Child class calling Parent class constructor using super keyword

class Parent
{
    String name;

    public Parent(String n) 
    {
        name = n;
    }
    
}
public class Child extends Parent {
    String name;

    public Child(String n1, String n2) 
    {
        
        super(n1);       //passing argument to parent class constructor
        this.name = n2;
    }
    public void details()
    {
        System.out.println(super.name+" and "+name);
    }
     public static void main(String[] args)
    {
        Child cobj = new Child("Parent","Child");
        cobj.details();
    }
}
Output
Parent and Child

Super class reference pointing to Sub class object.

In context to above example where Class B extends class A.
 A a=new B();
is legal syntax because of IS-A relationship is there between class A and Class B.

Q. Can you use both this() and super() in a Constructor?

NO, because both super() and this() must be first statement inside a constructor. Hence we cannot use them together.

 

1 comment: