开发者

inheriting method not working from parent class

开发者 https://www.devze.com 2023-03-03 12:41 出处:网络
I was wondering why my child class isn\'t inheriting correctly. if i had... public class ArithmeticOp{ //some constructor

I was wondering why my child class isn't inheriting correctly.

if i had...

public class ArithmeticOp{

    //some constructor

    public static void printMessage(){
        System.out.println("hello");
    }

}

and another class

public class AddOp extends ArithmeticOp{

    //some constr开发者_StackOverflow中文版uctor

    ArithmeticOp op = new ArithmeticOp();
    op.printMessage();           //returns error
}

my eclipse keeps returning "Syntax error on token "printMessage", Identifier expected after this token"

could someone please help? thanks! are there other ways to call methods from the parent class as well from a child class? thanks a bunch!


This is because you can't put arbitrary code into the class body:

public class AddOp extends ArithmeticOp{

    ArithmeticOp op = new ArithmeticOp(); // this is OK, it's a field declaration
    op.printMessage();                    // this is not OK, it's a statement
}

The op.printMessage(); needs to be inside a method, or inside an initializer block.

That aside, your code feels wrong. Why would you want to instantiate an ArithmeticOp inside one of its own subclasses?


It's because that method is declared as static. I may be mistaken and I'm sure someone will comment if I am but I think you can do:

public class AddOp extends ArithmeticOp{

    //some constructor

    ArithmeticOp op = new ArithmeticOp();
    super.printMessage();           //super should call the static method on the parent class
}

Or

public class AddOp extends ArithmeticOp{

    //some constructor

    ArithmeticOp op = new ArithmeticOp();
    ArithmeticOp.printMessage();           //Use the base class name
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号