Domanda

Can somebody please tell me if the keyword 'extends' must be an used (in the syntax) of child classes that overide methods of their super class.

È stato utile?

Soluzione

The word extends is used to indicate for the whole class that this class is a sub-class of another class. It is not related to whether the sub-class overrides certain methods or not, that is entirely up to the sub-class class. The sub-class may decide to override none, some, or all of the methods of the super-class. The sub-class may override only methods which are not marked as final in the super-class.

Here is a somewhat trivial example:

class A {
    // This is the super-class.
    public void myMethod() {...};
}

class B extends A { 
    // This extends above says: B is sub-class of A.
    // So this class B is the sub-class of A.
    // You can override methods of A here, like this
    public void myMethod() {...};
    // but you're not required to override them. 
}

Altri suggerimenti

Polymorphism in java is a concept by which we can perform a single action by different ways.it uses 2 concepts such as method overloading and method over riding. A method is a set of code which is referred to by name and can be called (invoked) at any point in a program simply by utilising the method's name. the method over riding concepts uses the key word 'extends'. We can extend a class by using the extends keyword in a class declaration after the class name and before the parent class.

      public class ParentClass {
       }

and we define child class like

       public class ChildClass extends ParentClass {
        }

// example of extending a class

  class B {
  int x = 0;
  void f1 () { x = x+1;}
  }

class C extends B {}

public class Test1 {
public static void main(String[] args) {
    B b = new B();
    b.f1();
    System.out.println( b.x ); // prints 1
 }
}

// example of extending a class, overwriting a method

   class B {
   int x;
   void setIt (int n) { x=n;}
   void increase () { x=x+1;}
   }

  class C extends B {
void increase () { x=x+2;}
}

public class Test2 {
public static void main(String[] args) {
    B b = new B();
    b.setIt(2);
    b.increase();
    System.out.println( b.x ); // prints 3

    C c = new C();
    c.setIt(2);
    c.increase();
    System.out.println( c.x ); // prints 4
    }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top