Wednesday, 19 April 2017

Abstract Classes

In general abstraction is nothing but hiding of irrelevant information.We Implement abstraction in oop using abstract classes and interfaces.


What is an abstract class


Abstract class implies that,it has one or more abstract method.An abstract method doesn't contain its implementation.


Why do we use Abstract classes:


Let us consider the following scenario.
We have a class named Automobile.It has a member function no_of_wheels.(every automobile has wheels). there are certain classes like Bike,Auto,Car,Bus etc.,.,which comes under automobile class. Here,all vehicles comes under automobile class,but they do not have all the properties same.For example number of wheels is different from each other.

Example:

import java.io.*;
abstract class Automobile
{
 abstract int no_of_wheels();
}
class Car extends Automobile
{
  int  no_of_wheels()
 {
  return 4;
 }
}
class Auto extends Automobile
{
 int no_of_wheels()
 {
  return 3;
 }
}
class Bike extends Automobile
{
 int no_of_wheels()
 {
  return 2;
 }
}
class MainClass
{
 public static void main(String args[])
 {
  Bike b=new Bike();
  Car c=new Car();
  Auto a=new Auto();
  b.no_of_wheels();
  c.no_of_wheels();
  a.no_of_wheels();
 }
}

Can we instantiate an abstract class ?


No,we cannot instantiate an abstract class i.e.,we cannot create an object.This is because,the keyword abstract itself says that it is incomplete.It is just a skeleton.One more thing is abstract methods are not implemented, So what should happen if you create an object for abstract class and try to access the method that doesn't have body? it's not going to work and may cause problem.So if abstract comes before a class name,then JDK tells to JVM to discard that class object initiation.

How to access Abstract Methods:


There are two ways of accessing abstract methods as follows.

1) Creating a reference for the base class.


import java.io.*;
abstract class Code
{ 
 void implement()
 {
 }

}
class Titans extends Code
{
 void implement()
 { 
  System.out.println("Inside Titans class");
 }
}
class MainClass
{
 public static void main(String args[])
 {
  Code c;//creating reference for the abstract class
  c=new Titans();
  c.implement();
 }
}

Output:

Inside Titans class
2)Creating an object for the child classes.


import java.io.*;
abstract class Code
{
  void implement()
  {
  }
}
class Titans extends Code
{
 void implement()
 {
  System.out.println("Inside Titans class");
 }
}
class Mainclass
{
 public static void main(String args[])
 {
  Titans t=new Titans(); //creating object for the derived class
  t.implement();
 }
}

Output:


Inside Titans class

No comments:

Post a Comment