Tuesday, February 8, 2011

Abstract class and abstract function in BlueJ

In a simple class in BlueJ, the data members of the class are declared and function members are defined. The members can have any access specifiers, public, private, protected or default. Function definition means where function return type, name, argument list (if no argument, it is kept blank)and function body is defined. Function body of a function should have an opening and closing curly brace.

Example of function definition:



public void setData( int x, int y)
{
Statement 1;
Statement 2;
……………..

}

If in any class a function is not defined as shown above, its prototype is simply declared then the keyword abstract should be used with the function otherwise compiler will show error.
.

Example of abstract function



abstract void set();

This above function has no body, it is not defined. Thus we can say that this function is incomplete. In java, incomplete function means abstract function. If a single function of a class is abstract then the class also becomes abstract class. An abstract class can have more than one abstract function. For abstract class, the keyword abstract should be used before the class name while defining the class otherwise compiler will show compile time error.

Example of abstract class definition



abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

Abstract class can have instance members as well as static members. Abstract can define it’s own constructor also but the only difference with abstract class is that objects of abstract class can not be created. We have defined an abstract class ‘MyClass’ just above. If we try to create object of this class using the statement MyClass obj=new MyClass(), it will show compile time error. Abstract class can be inherited by other class but the sub class would either override the abstract functions of the abstract super class or declare itself abstract class.

Example of abstract class inheritance



abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

class MyClass2 extends MyClass
{

void show()
{
System.out.println(“Value=”+a);
}
}

Here the sub class MyClass2 inherites the abstract class MyClass and the abstract function is overridden in the sub class. If the sub class MyClass2 do not override the abstract function then the codes would be like

abstract class MyClass
{
int a;
public void set()
{
A=10;
}
abstract void show();
}

abstract class MyClass2 extends MyClass
{

void showValue()
{
System.out.println(“Value=”+a);
}
}

Here in the above codes both the classes are abstract so objects of both the classes can not created. One point to be remembered that abstract class objects can be declared and it can refer its sub class object.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner