Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

Ways to Use Inheritance

There are two ways to use Inheritance in Java.

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.

Inheritance

In Java, the following terms are often used:

  • Super Class - the topmost part of the class
  • Parent Class - the class before the child class
  • Child Class - the last class in the program
To understand fully, here's a sample of a family tree.







Obviously, the child (classes) are the following:

  • Me
  • Brother
  • Sister
  • Cousin; and
  • OTHER Cousin
The Parent Classes are:
  • Mommy and Daddy Smith
  • Uncle and Aunt Trotter
  • Aunt and OTHER A.N
The Super Class are:
  • Grandad and Granny Jones
  • Great Grandad and Great Granny Bloggs
However, Java does not support multiple inheritance. Java can only hold one Super Class, one Parent Class, and one Child Class.

Extended Search

Custom Search
Hello World