class first
{
int number;
void Add()
{
number=number+1;
}
void Subtract()
{
number=number-1;
}
}
class second extends first
{
void Add()
{
number=number*1;
}
void Divide()
{
number=number/1;
}
}
public class MClass
{
public static void main (String args[])
{
first one = new first();
one.Add();
one.Subtract();
second two = new second();
two.Add();
two.Divide()
}
}
Given the code above, second extends first where second inherits first's methods and variable. As you can see the variable in class first and class second is the same, which is number, though number is only declared in class first. Class Second overrides the Add method and added a Divide method.
When class second extends to first, we call second as a subclass of first and first is the superclass of second. In java, two or more classes can inherit from the same parent class but a class can only have one parent.
No comments:
Post a Comment