Page 367 - CITS - Computer Software Application -TT
P. 367

COMPUTER SOFTWARE APPLICATION - CITS




               // private method in SuperClass
               private void privateMethod()
               {
                       System.out.println(

                              “This is a private method in SubClass”);
               }
               // This method overrides the public method in SuperClass
               public void publicMethod()

               {
                       System.out.println(
                              “This is a public method in SubClass”);
                       privateMethod(); // calls the private method in
                                                   // SubClass, not SuperClass
               }

           }
           public class Test {
               public static void main(String[] args)
               {

                       SuperClass obj1 = new SuperClass();
                       obj1.publicMethod(); // calls the public method in
                                                           // SuperClass
                       SubClass obj2 = new SubClass();
                       obj2.publicMethod(); // calls the overridden public

                                                           // method in SubClass
               }
           }
           5  The overriding method must have the same return type (or subtype)
           From Java 5.0 onwards it is possible to have different return types for an overriding method in the child class,
           but the child’s return type should be a sub-type of the parent’s return type. This phenomenon is known as the
           covariant return type.

           class SuperClass {
               public Object method()
               {
                       System.out.println(

                              “This is the method in SuperClass”);
                       return new Object();
               }
           }
           class SubClass extends SuperClass {
               public String method()



                                                           354

                             CITS : IT&ITES - Computer Software Application - Lesson 94 - 100
   362   363   364   365   366   367   368   369   370   371   372