Search code examples
javaooppolymorphismoverriding

Can a Java method in a sub class have the same signature as a method in the parent class but does not cause overriding?


I have recently started learning Java and currently studying about polymorphism. Consider the following code :

    public class Polygon{
       public static void perimeter( ){
             System.out.print("In Polygon perimeter");
       }
       public void area( ){
             System.out.println("In Polygon area");
       }
       public void sides( ){
             System.out.println("In Polygon sides");
       }
       public void angleSum( ){
             System.out.println("In Polygon angleSum");
       }
  }
  public class Pentagon extends Polygon{
       public static void perimeter( ){
             System.out.println("In Pentagon perimeter");
       }
       public void area( ) {
             System.out.println("In Pentagon area");
       }
       public int sides( ){
              return 5;
       }
       public void angleSum(int x) {
             System.out.println("In Pentagon angleSum");
      }
  }

On executing this code, I find out that sides() method cannot be overridden. I understand in overriding, the method name and return type should be same but in this case return types are different. So, is there any way to execute it without causing overriding but keeping the same names and different types?


Solution

  • is there any way to execute it without causing overriding but keeping the same names and different types?

    Only if the method in the parent class is declared as private, no overriding takes place, but the method sides has very limited access so the following code in Main.java class fails:

    class Polygon {
        private void sides() {
            System.out.println("In Polygon sides");
        }
    }
    
    class Pentagon extends Polygon {
        public int sides() {
            return 5;  // is not aware of `sides` in Polygon
        }
    }
    
    Polygon p = new Pentagon();
    p.sides(); // -> sides() has private access in Polygon
    

    Thus, method sides is accessible only for Pentagon instances/references:

    Pentagon p = new Pentagon();
    System.out.println(p.sides());  // -> 5
    

    If sides methods are declared as static in both classes having different return types, the code won't compile either:

    class Polygon {
        public static void sides() {
            System.out.println("In Polygon sides");
        }    
    }
    
    class Pentagon extends Polygon {
        public static int sides() {
            return 5; // sides() in Pentagon cannot hide sides() in Polygon
                      // return type int is not compatible with void
        }
    }