1. Using the Extend keyword
As you have learned from the previous lesson, the extend keyword is used in Method Overriding, which is a part of Polymorphism. We use it to refer the different methods and variables in a parent or super class that can be used in the parent of child class. Given the example from the previous post...
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()
}
}
2. Constructor Method
A constructor method is commonly used (beginners) in creating methods in a simple program. The constructor method uses parameters to connect values from the object class to the main class. For example, given a Sample Class and a Main Class...
class Sample
{
void test()
{
System.out.println("Test");
}
}
public class MainClass
{
public static void main (String args[])
{
Sample x = new Sample();
}
}
The output will only display Test.
No comments:
Post a Comment