Abstract classes in Java

By: Kamini Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

There are situations in which you will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. One way this situation can occur is when a superclass is unable to create a meaningful implementation for a method. This is the case with the class Figure used in the preceding example. The definition of area( ) is simply a placeholder. It will not compute and display the area of any type of object.

As you will see as you create your own class libraries, it is not uncommon for a method to have no meaningful definition in the context of its superclass. You can handle this situation two ways. One way, as shown in the previous example, is to simply have it report a warning message. While this approach can be useful in certain situations—such as debugging—it is not usually appropriate. You may have methods which must be overridden by the subclass in order for the subclass to have any meaning. Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want some way to ensure that a subclass does, indeed, override all necessary methods. Java's
solution to this problem is the abstract method.

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:

abstract type name(parameter-list);

As you can see, no method body is present. Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which implements that method:

// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}

class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}

Notice that no objects of class A are declared in the program. As mentioned, it is not possible to instantiate an abstract class. One other point: class A implements a concrete method called callmetoo( ). This is perfectly acceptable. Abstract classes can include as much implementation as they see fit.

Although abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature put to use in the next example. Using an abstract class, you can improve the Figure class shown earlier. Since there is no meaningful concept of area for an undefined two-dimensional figure, the following version of the program declares area( ) as abstract inside Figure. This, of course, means that all classes derived from Figure must override area( ).

// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}

class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}

class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

As the comment inside main( ) indicates, it is no longer possible to declare objects of type Figure, since it is now abstract. And, all subclasses of Figure must override area( ). To prove this to yourself, try creating a subclass that does not override area( ). You will receive a compile-time error.

Although it is not possible to create an object of type Figure, you can create a reference variable of type Figure. The variable figref is declared as a reference to Figure, which means that it can be used to refer to an object of any class derived from Figure. As explained, it is through superclass reference variables that overridden methods are resolved at run time.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(63)


1. View Comment

Awesome One....... Thanx...... m new to java...and its an awesome example to start up.

thanx a ton!!!!!
Cheers


View Tutorial          By: jayanta at 2010-02-05 04:35:34
2. View Comment

No use of this example.
I was searching other than java complete reference.
and these examples are copy and paste from Java complete reference book.


View Tutorial          By: Karan at 2010-04-10 05:41:47
3. View Comment

thanks for giving the example of abstract class...........

View Tutorial          By: mahesh at 2010-04-11 08:20:45
4. View Comment

Very good basic example. Thanks a lot..................

View Tutorial          By: satish at 2010-04-15 05:39:41
5. View Comment

that was gud example to explain abstract. i have doubt.....
here is one program which has 1 abstract class without abstract method. its also works fine.
Then what the use of abstract class, any how it does not allow to create objects, we can use this with concrete class to implement method defined in abstract class which we have to extend the abstract class then why not directly in concrete class why need of abstract class.
can anyone explain this point. mail me plz
zishan.infoapps@gmail.com

abstract class demo {
public void show() {
System.out.println("not abstract method");
}
// public abstract void display();
}
class demo1 extends demo {
public void display() {
System.out.println("abstract method");
}}

class program {
public static void main(String args[]) {
demo d = new demo1();
d.show();
d.display();
//d.display1();
}
}


View Tutorial          By: zishan at 2010-05-20 00:21:46
6. View Comment

Thanks a lot this thing was very importent for me!
holy007@i.ua


View Tutorial          By: Andrew at 2010-05-23 01:47:04
7. View Comment

A very nice example for abstract classes, simple but effective

View Tutorial          By: Rahul at 2010-06-16 20:45:24
8. View Comment

Awesome, I am Impressed with the way the example has been given here. It is such a great experience to go through this example of Abstract classes and methods in order to understand them so nicely. I am perfectly cleared with the Idea of Abstract Classes in JAVA Now.
Thank you so very much.


View Tutorial          By: Darshan at 2010-07-09 01:34:22
9. View Comment

yes it is very good example for Abstract classes and methods

View Tutorial          By: obulreddy.G at 2010-07-13 22:52:41
10. View Comment

yes,it is a very nice example for abstract classes and its methods.

View Tutorial          By: saranya at 2010-07-16 05:56:53
11. View Comment

yes it is good example for abstract classes.Thanks a lot this thing was very importent for me!

By : Nilesh chavan


View Tutorial          By: Nilesh Chavan at 2010-07-17 02:24:42
12. View Comment

Yeah..it's very good example....

View Tutorial          By: Packiyaraj.T at 2010-07-22 22:39:48
13. View Comment

i want diff example one.....

plz

give me


View Tutorial          By: Santhosh at 2010-07-30 01:35:22
14. View Comment

very very thankssssssssssssssss

View Tutorial          By: gowtham at 2010-07-31 22:58:36
15. View Comment

it is Marvelous example.

View Tutorial          By: princevijayakumar at 2010-08-04 07:56:33
16. View Comment

Thanks for giving this basic example of Abstract class. It will very help full in my next interview.

View Tutorial          By: Yogendra Kirar at 2010-08-07 07:48:34
17. View Comment

Very good explanation . I was very confuse but read this & my doubts are cleared . Thank you

View Tutorial          By: Shahabaj at 2010-08-10 08:58:39
18. View Comment

it's very easy simple progremme in java

View Tutorial          By: sambasiva rao at 2010-09-24 23:53:00
19. View Comment

yes it is very gud but i have still a doubt that is can we caal a derived class method by using object reference of EMPTY abstract class???????????

View Tutorial          By: Akheel at 2010-10-10 09:41:13
20. View Comment

This example is very useful to me,but i wnat more examples to clarify my doubts.plz send to my mail id......

View Tutorial          By: vaishali at 2010-12-06 08:20:18
21. View Comment

thanku very much. it is a good examples for abstract class

View Tutorial          By: rajesh at 2010-12-17 10:57:42
22. View Comment

Thank you very much. Now I know how to make an abstract class

View Tutorial          By: Alex at 2011-01-17 03:35:22
23. View Comment

realy it was a nice basic example...and better definition...my problem has solved after reading this...
thanks ....


View Tutorial          By: amit kumar at 2011-03-14 08:11:31
24. View Comment

Thks a lot..... The way of giving explanation and exmples are hossom to see and learn...for beginners it will be the best one..Can anyone provide me a complete learning refference for java like the above example.
If so plz do send me to my email.

harip.success@gmail.com


View Tutorial          By: Hari at 2011-04-08 02:58:06
25. View Comment

Abstract class example is good, What is the difference between abstract and interface . And give example with answer, it is most useful for us.

View Tutorial          By: megakumar at 2011-04-10 04:15:10
26. View Comment

Nice Example .........than Q!!!

View Tutorial          By: Sreekar at 2011-06-29 15:31:50
27. View Comment

neded defination in clear

View Tutorial          By: venkat at 2011-07-04 06:31:19
28. View Comment

Abstract class is a class that can not be instantiated, it exists extensively for inheritance and it must be inherited.

View Tutorial          By: Abstract at 2011-07-19 01:14:09
29. View Comment

thanx it i very helpful 4 me as i m new with java

View Tutorial          By: akminder at 2011-08-09 05:09:19
30. View Comment

copy of h.sheld

View Tutorial          By: vivek at 2011-08-31 13:12:36
31. View Comment

thanx. for this tutorial. i was having some doubt on abstract class. now, its clear.

View Tutorial          By: prabhash at 2011-09-06 10:15:19
32. View Comment

Here i posted a good example with spring. Here really implementation of OOPS.
public abstract class Shape {
public abstract double getArea();
public void printInfo()
{
System.out.printf("%s with area of %,.2f%n",getClass().getSimpleName(), getArea());
}



public class Circle extends Shape {

private double radius;

public double getRadius() {
return radius;
}

public void setRadius(double radius) {
this.radius = radius;
}

@Override
public double getArea() {
return Math.PI*getRadius()*getRadius();
}
public Circle(double radius)
{
setRadius(radius);
}

}


public class Rectangle extends Shape {

private double length,width;

public double getLength() {
return length;
}

public void setLength(double length) {
this.length = length;
}

public double getWidth() {
return width;
}

public void setWidth(double width) {
this.width = width;
}

@Override
public double getArea() {
return getLength()*getWidth();
}
public Rectangle(double length,double width)
{
setLength(length);
setWidth(width);
}
public Rectangle(){}

}


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class ShapeTest {

/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
Shape shape=(Shape)applicationContext.getBean("Rectangle");
shape.printInfo();

Rectangle rect=(Rectangle)shape;
rect.setLength(15.0);
rect.setWidth(10.0);


Shape shape2=(Shape)applicationContext.getBean("Rectangle");
shape2.printInfo();

Shape shape1=(Shape)applicationContext.getBean("Circle");
shape1.printInfo();
}

}


View Tutorial          By: Vikash K Agarwal at 2011-11-02 12:02:50
33. View Comment

thnks lot 4 helping me

View Tutorial          By: sandeep dudi at 2011-11-17 06:06:03
34. View Comment

ok this is gud example to build an abstract class. but i want know that what is the actual use of abstract class, why it is importent and what is the need of abstract class. i hope ill get perfact and more close answer to my question with an example. thanx

View Tutorial          By: ashish at 2011-12-01 06:22:32
35. View Comment

If one can't use English grammar correctly and with sense, how can one understand a programming language which is more difficult? Makes a lot of sense since one uses the same standards in programming JAVA...

View Tutorial          By: Java Man at 2011-12-09 06:04:14
36. View Comment

thanks for this example

View Tutorial          By: hai at 2011-12-16 05:36:14
37. View Comment

what is the meaning of instantiated in abstract class?

View Tutorial          By: Manikandan MP at 2011-12-20 15:17:38
38. View Comment

its very good example explains what is an abstarct class easily

View Tutorial          By: sandeep at 2012-01-06 07:13:29
39. View Comment

good start up fr java beginers

View Tutorial          By: sandeep Ch at 2012-01-06 07:16:34
40. View Comment

nice example for understanding abstract class,,,but its a basic one not covered details..anyway gud....

View Tutorial          By: Aavez Sk at 2012-01-17 09:44:36
41. View Comment

its very good , good example for beginners

View Tutorial          By: Rohit Mumbai at 2012-02-03 06:59:13
42. View Comment

really very good example .now i have cleared what is abstract class.java-samples is extremely good solution for who wants to learn java at home.

View Tutorial          By: pushpendra bansal gurjar at 2012-02-15 12:19:58
43. View Comment

abstract class Explain the concept of abstract class and it?s use with a sample program. Java Abstract Class An abstract class is a class that is declared by using the abstract keyword. It may or may not have

View Tutorial          By: rahul at 2012-02-23 08:30:47
44. View Comment

Before i had lot of doubts in abstract class... now i am clear with in this... Thank you very much

View Tutorial          By: Mohandoss at 2012-04-02 05:08:43
45. View Comment

abstract class A {
abstract void callme();

void callmetoo() {
System.out.println("This is a concrete method.");
}
}

class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}

class AbstractDemo {
public static void main(String args[]) {
B b = new B();

b.callme();
b.callmetoo();
}
}satish


View Tutorial          By: satish at 2012-04-07 10:35:38
46. View Comment

if a class is declared as abstract and it contains two abstract methods those methods should be called in the subclass and it is known as overriding the abstract method

abstract method can be override and it also be inherited.
by nagaraj


View Tutorial          By: nagaraj at 2012-04-25 17:12:30
47. View Comment

nicely explained :)

View Tutorial          By: ibtisam at 2012-04-26 10:31:58
48. View Comment

Thnaks a lot. Deep in brief.

View Tutorial          By: Thanks at 2012-05-23 03:36:37
49. View Comment

Hello to Every one!! :-),HERE I'AM NOT WRITING A CODE BECZ IT WILL TAKE A LOTS OF SPACE,SO I'AM JUST GIVING EXPLANATIONS TAT WAT IS ABSTRACT CLASS,BUT AFTER READING DIS EXPLANATIONS ALSO IF NYONE WILL NOT UNDERSTAND THEN AFTER TAT I'LL WRITE D CODE ALSO,so firstly we'll go to the "Abstract Method" before "Abstract Class,so wat is Abstract method?? so Method u all know is like a fucntion in C++ or C,just name is changed otherwise no differences r der,so "abstract method is a method without body",an abstract method is written when d same method has to perform different tasks depending on the object calling it,nd "ABSTRACT CLASS is a class tat contains 0 or more abstract methods, i mean in other words for Eg- if we want to calculate the square value in a Java program,so let we took a function named "calculate()" nd class named"Myclass" in a program,nd after tat we provide body for calculate() method,also we took three objects named obj1,obj2,obj3,now after dis u all r already know how to write a program of square value,actualy i'am not concentrating on square value program,i'am concentrating on the "BODY" of calculate() method,dis means as we written a body for calculate() method,so tat it is commonly available to all d objects -obj1,obj2,obj3,means requirements of all d objects is same,i.e "to calculate the square value",but sometimes the requirements of all d objects will be different depending on the objects,for eg-like first object(obj1) wants to calculate square value,second object(obj2) wants the square root value,nd third object(obj3) wants cube value,then wat to do now??its simple,firstly just write a calculate() method in "Myclass",dis means every object wants to calculate something,after tat dont write body for calculate() method,so tat it will not be commonly available to all d objects-obj1,obj2,obj3,so such a method is called as a "Abstract Method",in dis way we write abstract method in Myclass,then it is called as "Abstract Class",now derive sub classes from Myclass,tat means firstly derive sub class Sub1 from Myclass,so tat the calculate() method is available to d sub class,now provide a body for calculate() method in sub1 so tat it calculates square value,//ly we create another sub class Sub2 ,where we write the calculate() method with body to calculate square root value,then we again create d third sub class Sub3 where we write the calculate() method to calculate cube value,in dis way we'll create sub classes,nd after tat in another class u all r already know tat how to create sub class objects to call these classes methods,like Sub1 obj1=new Sub1(); Sub2 obj2=new Sub2();Sub3 obj3=new Sub3(); now after tat these objects will call,like dis- obj1.calculate(4);//calculate square,obj2.calculate(16); // calculate square root,obj3.calculate(3); // calculate cube value,so frnds the main concentration was on the "METHOD BODY",so in short "abstract method is a method without method body nd is written when the same method has to perform different tasks depending on the object" nd "abstract class is a class tat contains abstract methods",thanx,i'am waiting for ur comments... :-)

View Tutorial          By: Pulkit Malviya at 2012-08-26 14:56:18
50. View Comment

we can create reference variable for an abstract class but we cant call a method in the subclass , which is not available in the abstract class. wit h the reference variable we can call only those methods which are available in the superclass(here abstract class)

View Tutorial          By: siva at 2012-08-30 06:03:50
51. View Comment

thanku this is very good example

View Tutorial          By: priyanka at 2012-10-02 13:08:49
52. View Comment

Hi : Pulkit Malviya .I think that book has coding example also so once again refer that book clearly

View Tutorial          By: Anand at 2012-11-04 14:13:50
53. View Comment

Interfaces contains all abstract methods(with out logic or body for method) it means every method of Interface must be implemented in sub classes......
whereas in abstract classes contains 1 or more abstract method and may not be ...


View Tutorial          By: Mahesh at 2012-11-09 06:14:47
54. View Comment

/* File name : Employee.java */
public abstract class Employee
{
  private String name;
  private String address;
  private int number;
  public Employee(String name, String address, int number)
  {
     System.out.println(\"Constructing an Employee\");
     this.name = name;
     this.address = address;
     this.number = number;
  }
  public double computePay()
  {
    System.out.println(\"Inside Employee computePay\");
    return 0.0;
  }
  public void mailCheck()
  {
     System.out.println(\"Mailing a check to \" + this.name
      + \" \" + this.address);
  }
  public String toString()
  {
     return name + \" \" + address + \" \" + number;
  }
  public String getName()
  {
     return name;
  }
  public String getAddress()
  {
     return address;
  }
  public void setAddress(String newAddress)
 {
     address = newAddress;
 }
 public int getNumber()
 {
    return number;
 }
}

you can look at this example


View Tutorial          By: Anonymous at 2012-11-16 12:23:17
55. View Comment

hi What is the meaning of this line ,
you cannot declare abstract constructors, or abstract static methods.
---------------------
in ur example u have taken a constructor

abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
------------

can we take a constructor in abstract class


View Tutorial          By: Anil Chalhotra at 2013-02-16 08:04:03
56. View Comment

thanks for all samples..

View Tutorial          By: 珠洲市 at 2013-03-01 09:47:46
57. View Comment

super......... thanks 4 ur great example...

View Tutorial          By: jithinraj at 2013-03-13 08:34:07
58. View Comment

nice 1

View Tutorial          By: vivek at 2013-03-19 16:25:47
59. View Comment

Which one is the inbuilt Abstract class in java

View Tutorial          By: vikas jain at 2013-04-16 07:25:33
60. View Comment

A very good example to kickstart my preparation on abstract classes and methods

View Tutorial          By: Javaenthu at 2013-07-28 06:35:44
61. View Comment

The above example for abstract class is very good.sir i have a doubt,how develop a message abstract class contain play message abstract method?plz send the answer for that to my email.iam waiting for ur replay!

View Tutorial          By: saafia at 2013-08-19 14:33:54
62. View Comment

we can write an abstract class without any abstract methods.its true.bt wats the use?

View Tutorial          By: keerthi at 2013-08-20 16:31:38
63. View Comment

that's what I've been looking for!!!!!!!!!!!!!!!!!!!!!!!!!! Thx

View Tutorial          By: bibi at 2014-12-28 20:43:56

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Kamini
Importing the Certificate Reply from the CA example using keytool in Java
The switch Statement example in Java
Joins example in SQL
ERRNO.H Header File in C
XDoclet struts-config.xml in Struts
Macro Substitution using #define in C
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Do while Loops in C
Functions in C
Opening files for read and write in C++
Operator Precedence in C++
StringItem sample program in J2ME
AWT-based applications with a User Interface Window in Java
store() and load() example in Java
Stray or Dangling Pointers in C++

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to use ArrayList in Java
Student marks calculation program in Java
Count number of vowels, consonants and digits in a String in Java
FileReader and FileWriter example program in Java
Execute system commands in a Java Program
Palindrome String in Java
Why java is important to the Internet
Calculate gross salary in Java
Vector example in Java
Read from a COM port using Java program
Tomcat and httpd configured in port 8080 and 80
The Unary Operators example in Java
right shift operator, >>, in Java
Integer: byte, short, int, and long data types in Java
XML and Java - Parsing XML using Java Tutorial
Most Emailed Articles (in Java)
Using Charts in JasperReports
Introducing Nested and Inner Classes
Tomcat and httpd configured in port 8080 and 80
List all the serial and parallel ports in your system using Java
What is Unicode?
FileReader and FileWriter example program in Java
FilenameFilter - sample program in Java
Basics of Inheritance in Java
Method Overloading (function overloading) in Java
while - Iteration in java
how to use boolean data type in Java
equals( ) Versus == in Java
J2EE Components
Increment and Decrement Operator
Read from a COM port using Java program