Salman_Khan
Salman_Khan

Reputation: 89

how to call a base class method by super keyword

class base
{
    public void superMethod()
    {
        System.out.println("Hello i m a super class method");
    }
}

class der extends base
{
    super.superMethod();// error identifier expected 
}

i need to call a base class method without overloading it into derive class please provide me solution for it

Upvotes: 2

Views: 7577

Answers (5)

krakover
krakover

Reputation: 3029

You can't put code inside a method. The following should work:

class base {
    public void superMethod() {
        System.out.println("Hello i m a super class method");
    }
}

class der extends base {
    public void someMethod() {
        super.superMethod();
    }
}

Upvotes: 4

deepak
deepak

Reputation: 1

class base{
    public void superMethod(){
        System.out.println("hello i am super class method");
    }
}
class der extends base{
    void supermethod(){
        super.superMethod();
        System.out.println("hello this is der class");
    }
}
class mainclass{
    public static void main(String[] args){
        der r=new der();
        r.supermethod();
    }
}

Upvotes: 0

Abhishekkumar
Abhishekkumar

Reputation: 1102

You can call the super class method following the below example.

class base
{
    public void superMethod()
    {
        System.out.println("hello i m a super class method");
    }
}

class der extends base
{
    {
        super.superMethod();
    }
}

class Supertest
{
    public static void main(String args[])
    {
        new der();
    }
}

Upvotes: 1

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

You don't have to do anything apart from calling the method. You do need to be inside a instance method, constructor or a instance initializer block to do that though. You only need the super keyword if you have to make a distinction when you are overriding the method.

class Base
{
 public void superMethod()
 {
  System.out.println("Hello i m a super class method");
 }
}
class Der extends base
{
  public void method()
  {
     superMethod();// error identifier expected 
  }

  public void superMethod()
  {
     super.superMethod()
  }
}

Upvotes: 4

Jonathan B
Jonathan B

Reputation: 1061

You don't need to do anything special. Just call the method in the base class. Since you have not overloaded it, it will automatically call the base class method.

Upvotes: 2

Related Questions