Broad Network


Inheritance in Java Classes

Java Object Oriented Programming Core – Part 8

Forward: Inheritance is the ability to define new classes using existing classes as a basis. I explain that in this part of the series.

By: Chrysanthus Date Published: 3 Sep 2012

Introduction

This is part 8 of my series, Java Object Oriented Programming Core. Inheritance is the ability to define new classes using  existing classes as a basis. I explain that in this part of the series.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at  forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

New Members
Remember, a member is a property or a method. You can have a class with its members. Then you want a new class that will have  those same members and new members. Are you going to describe (created) a new class retyping the same old members of the  existing class plus new members? Java exists in such a way that you can have a class with its members and then a new related  class with the same members as those of the existing class and with its own new members. So, if you want a class that simply  has extra members in addition to what an existing class has, you inherit (see below) it from the existing class adding the  new members.

Example
The following code shows a class with two properties and one method. The method adds the values of the two properties:

class Calculator
    {
        int num1;
        int num2;

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    }


class InheritEx
    {
        public static void main(String[] args)
            {
                Calculator myObject = new Calculator();
                myObject.num1 = 6;
                myObject.num2 = 7;
                int result = myObject.add();
                System.out.println(result);
            }
    }

Imagine that you want a class that would square a sum (a sum is the addition of two values) and add a fixed value (say 5) to  the square. We already have a class that does summing of two values. So, we can derive a class from this existing class. The  derived class is the inherited class. It will have an additional property, which holds the fixed value (5). It will have an  additional method that squares the sum and adds the fixed value. It inherits the two properties and the add() method of the  existing class. The syntax to derive one class from another is:

    class subclassName extends superclassName
        {
            //new members
        }

You begin with the reserved word, class. This is followed by the name of the derived (inherited) class. Next you have the  reserved word, extends. Then you have the name of the existing class. The existing class is called the base class or  superclass. We say the derived class is inherited from the superclass. After the superclass name is typed above, you have to  describe (code) the derived class (new properties and new methods) within curly braces. The following code shows how you  derive a class using the above-mentioned base and derived class outline:

class Calculator
    {
        int num1;
        int num2;

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    }

class ChildCalculator extends Calculator
    {
        int fixedVal;

        int square(int answer)
            {
                int finalVal = answer * answer + fixedVal;
                return finalVal;
            }
    }


class InheritEx
    {
        public static void main(String[] args)
            {
                ChildCalculator myChildObj = new ChildCalculator();
                myChildObj.num1 = 2;
                myChildObj.num2 = 3;
                int result = myChildObj.add();
                myChildObj.fixedVal = 5;
                int endResult = myChildObj.square(result);
                System.out.println(endResult);
            }
    }


Before we continue, know that the derived class is also called the subclass or child class.

The superclass calculator has two properties and one method. The subclass has one property and one method. The value that  will be assigned to the property of the subclass is considered as the fixed value. The method of the subclass, squares its  argument and then adds the value of its property to the square.

Now, in the main function: The first line instantiates a subclass object from the corresponding subclass. In this code, no  object has been instantiated from the superclass; that is not necessary as the subclass inherits all the members of the  superclass. The next statement in the main function assigns a value to one of the inherited properties of the subclass object  (class). The following statement does a similar thing. The fourth statement, which comes after, calls the inherited add()  method of the subclass object and the values of the inherited properties are summed. The return value of the inherited add()  method is assigned to the primitive object, result.

The fifth statement assigns a fixed value of 5 to the only property that belongs to the subclass object. The statement after,  calls the square() method that belongs sorely to the subclass object, sending the returned value (result) of the inherited  method as argument. The square method squares the sum (result) and adds the fixed value; so strictly speaking, this method  should not really be given the name, square. The returned value of the square() method is displayed by the print statement,  next.

So a subclass has inherited members that it can use. It can also have its own new members. A subclass object is instantiated  from the subclass. A superclass object is instantiated from the superclass. The instantiated subclass and the instantiated  superclass are normally independent.

You can still derive a class (and corresponding object) from a subclass to have a grandchild. In this case the former child  class becomes the superclass and the new child class becomes the subclass. The chain can grow downward.

The Constructor
The programmer defined constructor is not inherited. The above program does not have a programmer defined constructor. The  subclass can however use the superclass constructor indirectly as the following program illustrates:

class Calculator
    {
        int num1;
        int num2;

        Calculator (int ident1, int ident2)
            {
               num1 = ident1;
               num2 = ident2;
            }

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    }

class ChildCalculator extends Calculator
    {
        int fixedVal;

        ChildCalculator (int ident1, int ident2)
            {
                super(ident1, ident2);
            }

        int square(int answer)
            {
                int finalVal = answer * answer + fixedVal;
                return finalVal;
            }
    }


class InheritEx2
    {
        public static void main(String[] args)
            {
                ChildCalculator myChildObj = new ChildCalculator(2,3);
                int result = myChildObj.add();
                myChildObj.fixedVal = 5;
                int endResult = myChildObj.square(result);
                System.out.println(endResult);
            }
    }

The constructor in the subclass declaration is:

        ChildCalculator (int ident1, int ident2)
            {
                super(ident1, ident2);
            }

It has the same name as the subclass. There is a method call, which is, super(). This call can take arguments. As said above,  the constructor of the superclass is not inherited, however, it can be used indirectly. The indirect use is possible with the  super() call that stands alone, without a preceding object (or class) variable and dot. The arguments for the method are the  parameter names of the actual super constructor, without the preceding data types. Read and try the above code if you have  not already done so.

In the above program, the constructor of the subclass initializes only the inherited properties. What about the case when the  subclass constructor has to initialize both the inherited properties as well as its own properties? In this case the subclass  constructor will have additional initialization statements of its own. Read and try the following code:

class Calculator
    {
        int num1;
        int num2;

        Calculator (int ident1, int ident2)
            {
               num1 = ident1;
               num2 = ident2;
            }

        int add ()
            {
                int sum = num1 + num2;
                return sum;
            }
    }

class ChildCalculator extends Calculator
    {
        int fixedVal;

        ChildCalculator (int ident1, int ident2)
            {
                super(ident1, ident2);
                fixedVal = 5;

            }

        int square(int answer)
            {
                int finalVal = answer * answer + fixedVal;
                return finalVal;
            }
    }


class InheritEx3
    {
        public static void main(String[] args)
            {
                ChildCalculator myChildObj = new ChildCalculator(2,3);
                int result = myChildObj.add();
                int endResult = myChildObj.square(result);
                System.out.println(endResult);
            }
    }

If you do not want to use the super constructor indirectly, then just write a completely new constructor for the subclass.


That is it for this part of the series; we continue in the next part.

Chrys
NEXT

Related Articles

Java Course

Comments

Become the Writer's Fan
Send the Writer a Message