Jeremy Kaplan
Jeremy Kaplan

Reputation: 11

Call an overriden method from the super class

I have a question about overriding methods. if i have class a that has a method that can be overriden by the subclasses but is called in the superclass

public class a {
  //this is the main class
  public a() {
       //etc code
       callMethod();
   }
   void callMethod() {
       //do nothing here. will be overriden in subclas
  }

  public class b extends a {
      void callMethod() {
           //actually impliment here
  }
  }

how to I call class b's implimentation of the method from class a

Upvotes: 0

Views: 232

Answers (5)

ollins
ollins

Reputation: 1849

public abstract class a {
  //this is the main class
  public a() {
       //etc code
       callMethod(); 
   }
   abstract void callMethod();
}

  public class b extends a {
      void callMethod() {
           //actually impliment here
  }
}

But don't do this. This calling method from constructor in superclass a maintenance nightmare and bad design.

Upvotes: 0

Jeff Ferland
Jeff Ferland

Reputation: 18312

The following results in a compiler error: "An enclosing instance that contains Demo.A.B is required." That is discussed in: An enclosing instance that contains <my reference> is required. So, the answer is: You can't do that. Write it into its own class file instead of a nested class.

package Demo;

import Demo.A.B;

public class Demo {
    public static void main(String[] args) {
        A test = new B();
    }
}

Broken

Package Demo;

public class A {

    public A() {
        callMethod();
    }

    void callMethod() {
        System.out.println("Called from A");
    }

    public class B extends A {
        @Override
        void callMethod() {
            System.out.println("Called from B");
        }
    }
}

Working

(A.java)

Package Demo;

public class A {

    public A() {
        callMethod();
    }

    void callMethod() {
        System.out.println("Called from A");
    }
}

(B.Java)

package Demo;

public class B extends A {
    @Override
    void callMethod() {
        System.out.println("Called from B");
    }
}

Upvotes: 0

Sergii Zagriichuk
Sergii Zagriichuk

Reputation: 5399

you cannot but you can create constructor for class b, call workflow will be next fileds a - > constructor a - > method from a-> constructor b - > method from b

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340963

Probably you meant:

public class b extends a

In this case the code:

a aa = new b();

Will call b.callMethod(). Note that calling overriden (non-private) methods from a constructor is a bad idea.

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81154

If you change the visibility of the callMethod method to protected then b.callMethod() is what would be called, even from the superclass.

The protected keyword tells Java that the method is visible to subclasses; and by extension makes it virtual.

Upvotes: 0

Related Questions