0
1.4kviews
Short note on abstract method and classes.

Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology

Marks: 5M

Year: Dec 2013, May 2014, May 2015

1 Answer
0
1views
  • Sometimes we may want to create a super class that only defines a generalized form that will be shared by all of its subclasses. So it’s a responsibility of each subclass to fill in the details.
  • This super class declares the structure of a given abstraction without providing a complete implementation of every method and thus, compulsory for subclass to override a method.
  • Such a class determines the nature of the methods that the subclasses must implement. This can be done by creating a class as an abstract.
  • This can be achieved by preceding the keyword ‘abstract’ in the method definition with following form:

    abstract datatype methodname(parameters);
    
  • There is no method body present. Any class that contains one or more abstract methods must also be declared as abstract. To declare a class abstract, we have to write ‘abstract’ in front of keyword ‘class’ in the definition. For example:

    abstract class White
    {
     ……
    abstract void paint();
    ……
    ……
    }
    
  • We cannot create the 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, we cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the super class, or be itself declared abstract.

Example of abstract class and methods.

//Abstract class and method
abstract class Maths
{
int var1, var2, var3;
abstract void calculate();
void addition()
{
    var3 = var1 + var2;
        System.out.println("Addition : "+var3);
}
}
class Arithmetic extends Maths
{
Arithmetic(int x,int y)
{
    var1 = x;
    var2 = y;
}
void calculate()
{
    var3 = var1 - var2;
    System.out.println("Subtraction : "+var3);
}
}
class AbstractClass
{
public static void main(String args[])
{
    Arithmetic a = new Arithmetic(30,18);
    a.calculate();
    a.addition();
}
}

Using abstract class and method

Output:

Subtraction: 12

Addition: 48

As class ‘Maths’ is declared as abstract we cannot create object of this class. ‘Maths’ class has is own concrete method named ‘addition’. This is acceptable. The overridden method ‘calculate’ is declared abstract in the super class with empty implementation.

Please log in to add an answer.