Java Inheritance - calling superclass method

前端 未结 5 1235
遥遥无期
遥遥无期 2020-11-27 18:15

Lets suppose I have the following two classes

public class alpha {

    public alpha(){
        //some logic
    }

    public void alphaMethod1(){
        /         


        
相关标签:
5条回答
  • 2020-11-27 18:43

    It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

    If it depends on the situation, you can put some code logic like :

    public void alphaMethod1(){
        if (something) {
            super.alphaMethod1();
            return;
        }
        // Rest of the code for other situations
    }
    

    Like this it will only call A's method when needed and will remain invisible for the class user.

    0 讨论(0)
  • 2020-11-27 18:44

    Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.

    If you write super() at that time parents's default constructor is called. same if you write super.

    this keyword refers the current object same as super key word facilty for accessing parents.

    0 讨论(0)
  • 2020-11-27 18:55

    You can do:

    super.alphaMethod1();
    

    Note, that super is a reference to the parent, but super() is it's constructor.

    0 讨论(0)
  • 2020-11-27 19:03

    You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

    solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

    class Beta extends Alpha
    {
      public void alphaMethod1()
      {
        super.alphaMethod1();
      }
    }
    

    or from any other method of Beta like:

    class Beta extends Alpha
    {
      public void foo()
      {
         super.alphaMethod1();
      }
    }
    
    class Test extends Beta 
    {
       public static void main(String[] args)
       {
          Beta beta = new Beta();
          beta.foo();
       }
    }
    

    solution 2: create alpha's object and call alpha's alphaMethod1()

    class Test extends Beta
    {
       public static void main(String[] args)
       {
          Alpha alpha = new Alpha();
          alpha.alphaMethod1();
       }
    }
    
    0 讨论(0)
  • 2020-11-27 19:05

    Simply use super.alphaMethod1();

    See super keyword in java

    0 讨论(0)
提交回复
热议问题