CHAPTER 12

INHERITANCE

Let us imagine that a particular class is developed and used in some program. Now, another class is needed which is similar to this class but with more functionality (power). Does the time consumed in developing this class go waste? No, the Inheritance principle allows us to define a new class based on the previously designed class. We are required only to write a code related to additional functionality. The previously developed class is directly used. In technical jargon, the new class inherits the properties of old class.

12.1 Inheritance Basics

Consider a case where you want to develop class Time12. Assume that you have class Time24. Name Time24 stands for twenty-four hours clock. The hours can take values between 0 and 23. In our routine life, we are accustomed to 12-hour clock. A class Time12 need everything of Time24 but should also have something more, that is specification AM or PM. This is an ideal situation for inheritance.

Here we say that class Time12 inherits the properties of class Time24. Class Time24 will be called the super-class while class Time12 will be called the sub-class. (See Figure 12.1)

Consider the following declaration:

class Time12 extends Time24

{  String str;

}

Note the key word extends. It tells the compiler that sub-class Time12 inherits properties of super-class Time24. Note that in C++ terminology, these classes are called derived classes and base classes.

Let us see a concrete example.

Simple Inheritance

Figure 12.1 Simple Inheritance

Problem: Define class Time12 from class Time24.

Solution: See Program 12.1.

 

PROGRAM 12.1 Sub-Class extends Super-Class

 //     inher1.java

 class Time24

        { int numsec ; // (int n) ;

        } ;

 class Time12 extends Time24

        { String st1;

        } ;

 class inher1

 { public static void main (String argv[])

    { System.out.println("<---inher1.java--->");

      Time12 t1 = new Time12();

      t1.numsec =( 9*60+ 15)*60 ;// college opens in the morning

      if (t1.numsec >= 12*60*60) // 12 noon

                t1.st1 = "PM" ;

           else t1.st1 = "AM" ;

 

      System.out.println("Time in seconds " + t1.numsec);

 

      System.out.println("st1 is -->"+ t1.st1 +"<--");

    };

 }

If you run this program, you will get the following output.

 

Output

 <---inher1.java--->

 Time in seconds 33300

 St1 is -->AM<--

In the aforementioned example, class Time12 is derived from class Time24. Variable numsec (for number of seconds) belongs to class Time24. It is not redefined in class Time12. Object t1 is of class Time12. Still we could initialize t1.numsec. It means that numsec is a member of class Time12 now.

12.2 Member Access and Inheritance

As observed earlier, member access control is through keyword public and private. At this stage, we will be interested in knowing what happens to variables of super-class if keywords are declared specifically. The answer is simple and logical. The super-class variable declared public is available for use (accessible) in sub-class as observed in Program 12.1.

The nature of word private suggests that such a variable is not accessible in sub-class. This rule is tested in Program 12.11 in Section 12.10. Table 12.1 specifies these facts in tabular form.

 

Table 12.1 Access Control

Super-class access specifier Effect in sub-class
public accessible
private not accessible

It is not mandatory to specify either public or private. When no particular access specifier is used, the access is considered as default. It is also termed as “package access”.

At this moment, we are discussing small and simple programs (something like single-file programs of C++). So far, we have not used any user-defined packages. Under these circumstances, a member with default access specifier in super-class works as if declared public, as far as inheritance is concerned. Since it is more convenient to define variables without access specifier, we will use default access when we intend to use public access. See Program 12.12 in the end of chapter programs. At a later stage, we will study user-defined packages. We will study access default in detail at that time.

Inheritance is a mechanism that enables one class to inherit the behaviour and attributes of another class. However, we observe that the members marked private in super-class are not accessible in the sub-class. Hence, we cannot say that inheritance is a mechanism that enables one class to inherit all the behaviour and attributes of another class.

12.3 Keyword super

12.3.1 Use of super in sub-class constructor

Constructing a sub-class object

Any object needs a constructor for a disciplined initialization. The problem with sub-class is that it has to initialize not only its own (instance) variables but also the variables belonging to super-class.

While writing a sub-class constructor, we are supposed to initialize variables from super-class also. It means we have to call constructor for super-class. For this purpose, keyword super is used. If Time12 is a sub-class having Time24 as super-class and Time24 has constructor Time24(int h, int m, int s), then sub-class constructor must starts with a statement

super( int1,int2,int3);

where int1, int2, and int3 are any integer expressions.

For example, the constructor for sub-class Time12 will look like the following:

Time12(some_parameters)

      { super(h,m,s);// call to super-class constructor

                 statement_1;

                 statement_2;

            .

            .

      };

Here when a call to constructor of a sub-class is made, it first makes a call to constructor of super-class and then goes on initializing its own variables. We may say that “First statement of sub-class constructor should be call to super()”.

Let us see this in a working program.

Problem: Show the use of keyword super in sub-class constructor.

Solution: See Program 12.2.

 

PROGRAM 12.2 Using super I

 //       super1.java

 class Time24

         { int hour,minute,second ;

           Time24(int h,int m, int s )

             { hour = h ;

               minute = m ;

               second = s ;

             }

         }

 class Time12 extends Time24

        { String str;

          Time12(int h,int m, int s)

            { super(h,m,s);

              if (h>11) str = "PM" ;

                  else str ="AM" ;

            }

        }

 class super1

 {  public static void main (String argv[])

    { System.out.println("<---super1.java--->");

      Time12 t1 = new Time12(9,15,0) ;

      System.out.println(t1.str) ;

    };

 }

Please note that class Time24 has a constructor (int, int, int). The first statement of constructor of sub-class Time12 is super(h,m,s). It is used to initialize the variables of super-class.

If you run this program, you will get the following output.

 

Output

 <---super1.java--->

 AM

It is possible that the super-class may contain 2–3 constructors. In that case, sub-class constructor can call any of them. If super-class does not have any constructor, we have to call super without any parameters like super().

In Program 12.2, you cannot simply say super(); compiler will complain that “No constructor matching Time24 () found in class Time24”.

One may think that if we have to call a super-class constructor, why not say Time24(h,m,s) at this position? Well syntax rules do not permit it.

We have seen a rule that “First statement of sub-class constructor should be call to super()”. There are exceptions to this rule. When super-class has NO constructor or has a constructor without parameters (default constructor), we need not call super() in sub-class constructor. You can see this in Program 12.13 in end of chapter program.

12.3.2 Use of super in referencing a super-class variable

When a variable name, identical to that one in super class, is used in a sub-class, the variable from super-class gets hidden. Let us say that we define a variable hour in sub-class Time12 also. Now as far as object of the sub-class is concerned, it recognizes only one hour. The one which belongs to sub-class is recognised and the hour from super-class gets hidden. To refer to such a super-class variable, we have to use keyword super.

When we say

super.var_name

we are referring to a variable with name var_name present in super-class. Let us verify this in the following program.

Problem: Show that the keyword super used in sub-class refers to super-class variable.

Solution: See Program 12.3.

 

PROGRAM 12.3 Using super II

 //      super3.java

 class Time24

        { int hour,minute,second ;

          Time24(int h,int m, int s )

            { hour = h ;

              minute = m ;

              second = s ;

            }

        }

 class Time12 extends Time24

        { int hour ;

          String str ;

          Time12(int h,int m, int s)

            { super(h,m,s);

              if (h>12) hour = h-12 ;

                 else hour = h ;

              if (h>11) str = "PM" ;

                 else str = "AM" ;

            }

          void show_super()

          { System.out.println(super.hour);

          }

        }

 class super3

 {   public static void main (String argv[])

     { System.out.println("<---super3.java--->");

       Time12 t1 = new Time12(17,15,0) ;

       System.out.println("time is :" ) ;

       System.out.print(t1.hour+":"+t1.minute);

       System.out.println(":"+ t1.second+" " +t1.str);

       t1.show_super();

     };

 }

If you run this program, you will get the following output.

 

Output

 <---super3.java--->

 time is :

 5:15:0 PM

 17

Please note the word super.hour marked in bold. It refers to hour of super-class.

Also note that this has appeared in a method of a sub-class.

12.4 Use of this in Sub-Class Constructor

As mentioned earlier, the first statement in a sub-class constructor should be super(). This is true in principle. However, a minor variation can occur. The first statement can be this(ABCD) as well. Let us consider a case where class Guru is a super-class. Class Shishya extends class Guru.

Consider a case that we have a class Shishya with a valid constructor given as follows:

Shishya (String sy, String sx) // first constructor

           { super(sx);

             st2 = sy ;

           }

Now we want to have another constructor, say

Shishya (String sy)

You will immediately ask me what about sx, that is the value of the super-class variable. In light of previous example who is “Guru”?

In actual code for the constructor, we can call the previously defined constructor. This can be accomplished by a call using keyword this.

Shishya BOTTOM(String sy) // second constructor

     { this( sy , “GURU”); // note this

     }

In C++, there is a concept of default parameters. This example is somewhat similar to it.

Let us see this illustrated in the following program.

Problem: Write a program to demonstrate use of this in sub-class constructor.

Solution: See Program 12.4.

 

PROGRAM 12.4 Guru Shishya Example

 //     guru1.java

 class Guru

      {  String guruName ;

           Guru(String sx )

             { guruName = sx ; }

         } ;

 class Shishya extends Guru

         {  String shishyaName;

            Shishya( String sy )

              { this(sy, "Drona") ;

              }

            Shishya(String sy, String sx)

              { super(sx);

                shishyaName = sy ;

              }

           void display()

            {  System.out.println(" Guru-->" + super.guruName) ;

               System.out.println("Shishya -->" + shishyaName ) ;

            }

         }

 class guru1

 {   public static void main (String argv[])

     { System.out.println("<---guru1.java--->");

       // example 1

       Shishya sh1 = new Shishya ("Narendra", “Rmakrishna") ;

       sh1.display();

       // example 2

       Shishya sh2 = new Shishya ("Arjun") ;

       sh2.display();

     };

 }

If you run this program, you will see the following output.

 

Output

 <---guru1.java--->

 Guru-->Ramakrishna

 Shishya -->Narendra

 Guru-->Drona

 Shishya -->Arjun

In this example, first we have a call to constructor with two parameters, Narendra (Famous Swami Vivekanand) and Ramakrishna (Parmahansa). This was a normal example.

In second example, we have a call to constructor for Shishya with only one parameter, Arjuna. Here a call to first constructor (as it has only one parameter) is made. In the code, there is keyword this. Here actually this means Shishya. It means this stands for call to second constructor (with two parameters).

Users of C++ are aware of facility of functions with default parameters. This facility is absent in Java. The aforementioned example is an indirect use of methods (functions) with default parameters.

12.5 Creating a Multi-Level Hierarchy

So far, we have seen one class extending the other. It is quite possible that the other class itself is a sub-class of another. Then this becomes the example of multi-level hierarchy.

Figure 12.2 illustrates this situation.

We can study this with a simple program. For simplicity, we will use an artificial example. Let us consider an example of an address book. It will typically contain entries like name, telephone number, and city. We will introduce one attribute at a time.

Multi-Level Inheritance

Figure 12.2 Multi-Level Inheritance

Problem: Write a program to demonstrate multi-level hierarchy.

Solution: Let us take the example of an address book (See Program 12.5).

 

PROGRAM 12.5 Multi-Level Hierarchy

 //       multi1

 class multi1

 {   public static void main (String argv[])

     { int total ;

       System.out.println("<---multi1.java--->");

       System.out.println("");

       C me = new C("prof",24567890,"Mumbai");

       me.show();

     };

 }

 

 class A

     { public String name;

       A(String st1)

        { name = st1; }

       public void show()

        { System.out.println("name");

        }

     }

 class B extends A

     {

       public long telephone ;

       B(String st1,long tn)

        { super(st1);

         telephone = tn ;

        }

       public void show()

        { System.out.println(super.name + " " + telephone);

        }

    }

 class C extends B

    { public String city ;

      C(String st1, long n, String st3 )

        { super(st1, n);

          city = st3 ;

        }

      public void show()

        { System.out.println(name + " " + telephone+ " " + city);

        }

     }

If you run this program, you will get the following output.

 

Output

 <---multi1.java--->

 Prof 24567890 Mumbai

The aforementioned program works fine. It demonstrates multi-level inheritance. Please note that all the members were having public access. In an ideal situation data, members should be private. In that case, they will not be available to sub-classes. A simple program will fail to compile.

12.5.1 Keyword protected

Java offers the solution in terms of keyword protected. This access specifier works as private for outside world, but works as public for derived classes. Hence, it becomes extremely useful in multi-level inheritance.

Let us study it with the help of a program.

Problem: Write a program to demonstrate the use of access specifier protected in multi-level hierarchy.

Solution: Let us take a case of a telephone diary. Its entries may include name, telephone number, and a city. Let us create a simulated example from this. Let class A stores only name. Class B stores name and telephone number. The class C contains all the three entities. Class C extends class B, whereas class B extends class A. We will declare key fields as protected.

See Program 12.6.

 

PROGRAM 12.6 Keyword protected

 //     multi4

 class multi4

 { public static void main (String argv[])

   {

     System.out.println("<---multi4.java--->");

     System.out.println("");

     C me = new C("prof",24567890,"Mumbai");

     me.show();

     System.out.println( me.telephone);

   };

 }

 class A

   { protected String name;

     A(String st1)

      { name = st1; }

     public void show()

      { System.out.println("name");

      }

   }

 class B extends A

   {

     protected long telephone ;

     B(String st1,long tn)

      { super(st1);

      telephone = tn ;

      }

     public void show()

      { System.out.println(super.name + " " + telephone);

      }

   }

 class C extends B

     { public String city ;

       C(String st1, long n, String st3 )

        { super(st1, n);

          city = st3 ;

        }

     public void show()

      { System.out.println(name + " " + telephone+ " " + city);

     }

 }

If you run this program, you will get the following output.

 

Output

 <---multi4.java--->

 prof 24567890 Mumbai

 24567890

You can see that the method shown from class C is capable of accessing protected variables in its super-classes.

The last program line

System.out.println( me.telephone);

is more critical. Here we are accessing a protected variable of class B in method main(). This method main is a part of class named multi4. This class is not a sub-class of class B.

This calls for a review of accessibility once again. Table 12.2 describes the rules for accessing variables of a given class, say X from some other class Y. We are assuming a single-file environment. It means that the classes X and Y are in the same file. (Technically speaking, they are in the same package. We will discuss the details of package in a later chapter.)

 

Table 12.2 Access Control in Single File Programs

Access specifier in a given class X Accessibility in other class Y  
  When Y is Sub-class of X When Y is not a sub-class of X
public Accessible Accessible
protected Accessible Accessible
default Accessible Accessible
private Not accessible Not accessible

Anyone who will scrutinize the table carefully will come up with a simple rule. If the access specifier is private, the variable is not accessible; in other access specifiers the variable is accessible.

We have used the term “variable” for simplicity. The correct word should be a member, as it will mean both variables (fields) and methods.

When we write a single-file program, all the classes it contains belong to same (unnamed) package. Since no specific name is given to this package, it is referred as “unnamed package”, and hence, the abovementioned rules are applied.

12.6 Method overriding

When same name appears for methods in both super- and sub-class, only method from sub-class is invoked. That is why it is said that the method of sub-class overrides the super-class method. However, super-class method is not lost, it is available. It has to be called with keyword super (only inside sub-class method).

Problem: Write a program to demonstrate method overriding.

Solution: See Program 12.7.

 

PROGRAM 12.7 Method overriding I

 //      super5.java

 class Time24

        { int hour,minute,second ;

          Time24(int h,int m, int s )

            { hour = h ;

              minute = m ;

              second = s ;

            }

          void show()

           {System.out.printf("***%3d%3d%3d", hour,minute,second);

            }

        }

 class Time12 extends Time24

    { int hour ;

      String str ;

      Time12(int h,int m, int s)

        { super(h,m,s);

          if (h>12) hour = h-12 ;

              else hour = h ;

          if (h>11) str = "PM" ;

              else str = "AM" ;

        }

      void show()

        { System.out.printf("===%3d%3d%3d%3s ", hour,minute,second,str);

        }

      void show_super()

        { System.out.println("showing from super :");

          super.show();

        }

       }

 

 class super5

 {   public static void main (String argv[])

     { System.out.println("<---super5.java--->");

       Time12 t1 = new Time12(17,15,0) ;

       System.out.println("calling show of sub") ;

 //     System.out.print(t1.hour+":"+t1.minute);

       t1.show();

       System.out.println("calling method show_super()");

       t1.show_super();

     };

 }

If you run this program, you will get the following output.

 

Output

 <---super5.java--->

 calling show of sub

 === 5 15 0 PM

 calling method show_super()

 showing from super :

 *** 17 15 0

Please note that we have used characters *** in show of super-class. Also note that we cannot call it as t1.super.show(). Language does not allow us to do it. We have to embed this call in some other method. Here we have chosen a name show_super()to draw attention to this fact.

12.7 Using final in Inheritance

Keyword final plays many roles in the process of inheritance. It can be used for a class or any method of a class. Let us study these situations one by one.

12.7.1 Using final with a class

It is possible to declare a normally behaving class as final. However, we cannot use it as a super-class. Any sub-classing is not allowed. There are two ways to look at this. When you think that the development of a class is complete and nobody should modify it by extending it, then you can use this keyword final with that class.

The other way is you feel that development is incomplete and no one use it (by extending) until you complete its development.

12.7.2 Using final with a method of a super-class

It is possible to declare a method in a class as final. That class behaves normally. We are allowed to sub-class it. However, we cannot override that method in a sub-class. Any such attempt generates compile time error. We can see this principle in action at the end of chapter program.

12.8 Introducing Interface

There are two ways of looking at interface facility. First one is simplistic. It considers it as a mask or interpretation of behaviour. The second one is complex. It looks at it as an effective tool for multiple inheritance. C++ supports multiple inheritance while Java does not. Hence, this technique is useful to affect two super-classes for one sub-class. However, only seasoned programmers need this facility. So we will discuss this concept at a later stage.

At this stage, let us study what interface offers us in simple terms.

12.8.1 Defining an interface

An interface can be defined as follows:

  interface std // std = standard

  { void define();

    void show();

  };

Please note the following points with respect to the interface definition:

  • Interface definition starts with the keyword interface.
  • Next is interface name.
  • Then comes the definition within curly brackets.
  • Interface may consist of variables (not seen in previous example). They are declared as final.
  • There is no body to the methods defined.

12.8.2 Implementing interfaces

Once an interface is defined, one or more classes can implement it.

A typical class definition using an interface is shown as the following:

 class  money implements std

     { int rupee;

       int paise;

       public void init(int a, int b)

          { rupee =a; paise = b; };

       public void show()

        {System.out.println(“Rs “+ rupee + “=”+paise);

        } ;

       public void define() { rupee =100; paise = 0; };

     };

          Note the syntax:

       class   class_name implements interface-name

            {

            }

Please note that methods define and show are fully defined here. In interface, they were simply declared.

As a rule, these methods must be declared public.

As a rule, any normal class must fully define all the methods declared in the interface. Let us see a working program.

Problem: Write a program to illustrate interface.

Solution: See Program 12.8.

 

PROGRAM 12.8 Interface I

 //      impl33.java

 interface std  // std = standard

    { void define();

      void show();

    };

 class money implements std

        { int rupee;

          int paise;

          public void init(int a, int b)

            { rupee =a; paise = b; };

          public void show()

               { System.out.println(“Rs ”+ rupee + “=”+paise);

               } ;

          public void define() { rupee =100; paise = 0; };

        };

 class impl33

 {   public static void main (String argv[])

     { //int total ;

       money amt1= new money() ;

       money amt2= new money();

       System.out.println(“---impl33.java---”);

       amt1.init(20,30);

       amt2.define();

       System.out.println(“amt1 is ”);

       amt1.show();

 //      System.out.println(amt1.rupee + “ ” + amt1.paise);

       System.out.println(“amt2 is ”);

       amt2.show();

     };

 }

If you run this program, you will get the following output.

 

Output

 ---impl33.java---

 amt1 is

 Rs 20=30

 amt2 is

 Rs 100=0

12.8.3 Variables in interfaces

All variables in the interface are declared as final and initialized. Therefore, they serve as enumerated constants.

Consider that we are working with money. We know that when we specify amount, paise cannot be more than 99 and less than 0. Naturally, our program needs two constants. We can define an interface for it as follows.

  interface constP // constP = constants for paise

  { final int pmax =99;

       final int pmin = 0;

  };

Let us see a complete program.

Problem: Write a program to show the use of interface in supplying constants to a class.

Solution: See Program 12.9.

 

PROGRAM 12.9 interface Supplies Constants

 //      impl4.java

 interface constP // constP = constants for paise

    { final int pmax =99;

      final int pmin = 0;

    };

 class money implements constP

        { int rupee;

          int paise;

          money(int a, int b )

            { rupee =a; paise = b; };

          public void check()

            { if (paise > pmax)

                 System.out.println(“paise can not be more than ”+ pmax);

              if(paise < pmin)

                 System.out.println(“ paise can not be less than ” +pmin);

            };

        };

 class impl4

 {   public static void main (String argv[])

     { money amt1= new money(100,100) ;

       money amt2= new money(30,-20);

       System.out.println(“---impl4.java---”);

       System.out.println(amt1.rupee + “ ” + amt1.paise);

       amt1.check();

       System.out.println(amt2.rupee + “ ” + amt2.paise);

       amt2.check();

     };

 }

If you run this program, you will get the following output.

 

Output

 ---impl4.java---

 100 100

 paise can not be more than 99

 30 -20

 Paise can not be less than 0

At this stage, we have seen two different useful interfaces for class money. If we want to redefine a class with both of them, Java permits us to do so. We can define our class, say money1 as

  class money1 implements std, constP

     {

     }

As a rule, a class can have more than one interface.

12.9 Abstract Methods and Classes

Sometimes, at the start of the project, we may want to define a class which is just some sort of a template or guideline for development of further classes. In that case, we need not define the class completely. Such a class is called abstract class. It goes without saying that such a class cannot be instantiated.

Consider a case that we have a class test. It has a number called num and method to show it. We want that implementation of show is left to the users of this class. We may want to define this class as

  class test { int num;

               void show();

             }

This will not be acceptable to the compiler as there is no body to method show. A key word abstract comes in to a play.

We may write

 class test

     { int num;

       abstract void show();

     }

Here we are declaring method show() as abstract method. This is fine as far as method void is concerned. Still the code will not compile. It will ask you to declare a class as abstract.

It will be acceptable if we declare it as follows:

  abstract class test { int num;

                        abstract void show();

                      }

You may feel that there is redundancy in it. You are right. But this redundancy is deliberate. It increases the readability. When a programmer reads this code, he is not likely to miss that the class is abstract. He will also not miss the point that the method show() is abstract.

You can now extend this class yourselves. Only thing is that in the sub-class, you must define the method show. Let us study it with a program.

Problem: Write a program to study extending a class which is abstract class.

Solution: See Program 12.10.

 

PROGRAM 12.10 abstract class

 //       abst3.java

 abstract class test

     { int num;

       abstract void show();

     }

 class newtest extends test

    {  void show()

         { System.out.println(“num is ” +num);

         }

    };

 class abst3

 {   public static void main (String argv[])

     {   newtest nt = new newtest();

         System.out.println(“<---abst3.java--->”);

         nt.show();

     }

 }

If you run this program, you will get the following output.

 

Output

 <---abst3.java--->

 num is 0

Rules:

  1. A method declared without the body is an abstract method. Such a method has to be declared as abstract.
  2. A class containing an abstract method is an abstract class. Such a class must be explicitly declared as abstract.
  3. An abstract class cannot be instantiated.
  4. If a class extends an abstract class, it must define all the methods of the super-class, otherwise it has to be declared abstract.

12.10 Collection of Programs

12.10.1 private of super not accessible

Problem: Show that instance variable declared private in super-class is not accessible in sub-class.

Solution: See Program 12.11.

 

PROGRAM 12.11 private of super not Accessible

 //       inher12.java

 class Time24

     { private int numsec ; // (int n) ;

       Time24(int num )

       { numsec=num;}

     } ;

 class Time12 extends Time24

     { String st1;

       Time12(int n)

         { super(n);

           if ( n >= 12*60*60) // 12 noon

                    st1 = "PM" ;

                    else st1 = "AM" ;

         }

     } ;

 class inher12

 { public static void main (String argv[])

    { System.out.println("<---inher12.java--->");

      Time12 t1 = new Time12(3600);

      System.out.println("st1 is : " + t1.st1);

      System.out.println("variable numsec is :"+ t1.numsec);

     };

 }

If you compile this program, you will get the following errors.

Compilation Error inher12.err

 Compiling javac

inher12.java inher12.java:22: numsec has private access in Time24

     System.out.println("variable numsec is :"+ t1.numsec);

                                                  ^

1 error

press any key to continue

If you comment out the last line you will get the following output.

 

Output

 <---inher12.java--->

 st1 is : AM

The key word private (marked in bold in source code) creates the problems.

12.10.2 This program proves that default acts as public

Problem: Write a program to show that default in super is accessible.

Solution: We have seen program inher1 earlier. Let us use the same basic code. Let us remove either public or private to make access default (see Program 12.12).

 

PROGRAM 12.12 default of super is Accessible

 //     inher13.java

 class time0

         { int numsec ; // note absence of either

                       // public or private

         } ;

 class clock extends time0

         { String st1;

          } ;

 class inher13

 {   public static void main (String argv[])

    { int total ;

      System.out.println(“---inher13.java---”);

      clock clk1 = new clock();

      clk1.numsec = ( 9*60+ 15)*60 ;; // college opens in the morning

      if (clk1.numsec >= 12*60*60) // 12 noon

                  clk1.st1 = “PM” ;

             else clk1.st1 = “AM” ;

      System.out.println(“Time in seconds ” + clk1.numsec);

      System.out.println(“st1 is -->”+ clk1.st1 +“<--”);

    };

 }

If you run this program, you will get the following output.

 

Output

 ---inher13.java---

 Time in seconds 33300

 st1 is -->AM<--

12.10.3 Is super always needed in sub-class constructor?

Problem: Show that the use of keyword super in sub-class constructor is not needed under certain conditions.

Solution: There are two distinct cases. When we have super-class which does not have any constructor, we need not use super in sub-class constructor. Alternately, if super-class has a constructor with no parameters (default constructor), call to super is not needed (see Program 12.13).

 

PROGRAM 12.13 super not Required

 //     default1.java

 //     No constructor in super class

 class Super1

        { String st1=" ";

          int i;

          void init()

          { st1="I am super";}

         }

 class Sub1 extends Super1

         { String st2 ;

           Sub1(String sy)

             {

               st2 = sy ;

             }

          }

 class Super2

          { String st1;

            int i;

            Super2()

            { st1="I am super";}

          }

 class Sub2 extends Super2

          { String st2 ;

            Sub2(String sy)

              {

                st2 = sy ;

              }

            void show()

            { System.out.println(st1);

              System.out.println(st2);

            }

           }

 class default1

 {   public static void main (String argv[])

     {

       System.out.println("<---default1.java--->");

       System.out.println(" No constructor case ");

       Sub1 s1 = new Sub1("Java") ;

       System.out.println("st1 is -->"+ s1.st2 ) ;

       System.out.println(" Default constructor case");

       Sub2 s2 = new Sub2("I am sub") ;

       s2.show();

    };

 }

If you run this program, you will get the following output.

 

Output

 <---default1.java--->

 No constructor case

 st1 is -->Java

 Default constructor case

 I am super

 I am sub

Note the following points carefully.

First case: There is no constructor in super-class. Hence, we are not calling constructor of super-class explicitly. Still, object of sub-class comes into existence.

Second case: There is a constructor with no parameters. Here also no call to super is required.

12.10.4 A final class cannot be extended

Problem: Test whether a class declared as final can be sub-classed (extended).

Solution: See Program 12.14.

 

PROGRAM 12.14 Class Declared final I

 //      final1.java

 final class TOP

         { String st1 ;

           TOP() { st1=”Guru” ; }

           void show()

             { System.out.println(“+++ st1 is+++>”+ st1) ;}

          } ;

 class BOTTOM extends TOP

          { String st2;

            BOTTOM() { st2 = “Shishya” ; }

            void show()

              { System.out.println(“### st2 is###>”+ st2) ;}

            void attention()

              { super.show(); }

       }

 class final1

 {   public static void main (String argv[])

     { System.out.println(“---final1---”);

       BOTTOM b1 = new BOTTOM() ;

       b1.show();

       b1.attention();

     };

 }

If you compile this program, you will get the following error.

 

Output

 Compiling javac final1.java

 final1.java:8: cannot inherit from final TOP

 class BOTTOM extends TOP

                      ^

 1 error

 press any key to continue

Keywords

Abstract, abstract class, abstract method, access control, enumerated, constants, extends, final, implements, interface, method overriding, multiple, inheritance, private, public, super, this

RuleBook

method interface Methods declared in interface must be declared public in class definition.
method interface Any normal class (non-abstract) must fully define all the methods declared in the interface.
interface A class can have more than one interface.
variables interface Variables in interface must be declared as final.
final class A class declared final cannot be sub-classed.
final method A method declared as final cannot be overridden.
abstract method A method declared without the body is an abstract method. Such a method has to be declared as abstract.
abstract class A class containing an abstract method is an abstract class. Such a class must be explicitly declared as abstract.
abstract class An abstract class cannot be instantiated.
abstract class extending If a class extends an abstract class, it must define all the methods of the super-class. Other wise it has to be declared abstract.
sub-class constructor Every constructor of a sub-class must have a call to super-class constructor as a first statement. Only exception is when Super-class has no constructor or has a default constructor (one without parameters).
multiple inheritances Java allows multiple inheritances by means of interfaces.
Implements A class can use an interface by using the implements clause.
Inheritance Inheritance is a mechanism that enables one class to inherit, in general, the behaviour and attributes of another class. But we cannot say that it inherits all the behaviour and attributes.
override A method is overridden when another method with the same signature is declared in a sub-class.
override A final method cannot be overridden.
interface An interface can extend any number of interfaces.

C++ Corner

  1. There is no direct equivalent of interface in C++.
  2. In early days, there was no enum keyword in Java. If one wants enumerated constants in Java, one has to define and use a suitable interface. Recently in version 5, a class Enum has been introduced. It can provide enumerated constants in a disciplined way.

Review Questions

  1. What is the significance of keyword super?
  2. What is the use of keyword final in inheritance?
  3. What role does interface play in multiple inheritance?
  4. How interface can be used to provide enumeration?
  5. What is the meaning of abstract method?
  6. What is the advantage of declaring a class abstract? What is the major difference between extending classes and extending interfaces?
  7. Abstract identifier can be applied to classes as well as methods. Explain what this modifier indicates in each case.
  8. What is the difference between abstract and final class.
  9. Discuss the role of inheritance in object-oriented programming.
  10. What do you understand by implementing interfaces? Explain with an example.
  11. What is the difference between abstract class and an interface?
  12. What does the final keyword mean in front of a variable, a method, and a class?
  13. Write short notes on access specifiers public, private, and protected.
  14. Write short notes on interfaces in Java.
  15. Write short notes on Abstract classes in Java.

Exercises

  1. State whether following program will compile. If yes, describe the output. If no, give reasons

    ********************************************

    //     final2.java

    class TOP

           { String st1 ;

             TOP() { st1="Guru" ; }

             final void show()

                { System.out.println("+++ st1 is+++>"+ st1) ;}

            }  ;

    class BOTTOM extends TOP

            { String st2;

              BOTTOM() { st2 = "Shishya" ; }

              void show()

                { System.out.println("### st2 is###>"+ st2) ;}

              void attention()

                { super.show(); }

             }

    class final2

    {   public static void main (String argv[])

        { System.out.println("---final2---");

          BOTTOM b1 = new BOTTOM() ;

          b1.show();

          b1.attention();

        };

    }

    ********************************************

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.227.9