首页 > 解决方案 > 不能在子类 JAVA 和一个子类中调用超类的方法

问题描述

我是 Java 和 OOP 的新手,我有一个像上面这样的超类和一个子类。当我尝试在子类中继承超类的方法并编译代码时,它给了我一个@782a9122 结果。我哪里错了??

感谢您的帮助。

class A {
    // to inherit from normal class => use `extends` keyword 
    // to inherit from interface class => use `implements` keyword 
    private int _x, _y;
    
    public A(int x, int y) {
        this._x = x;
        this._y = y;
    }
    public int getX() {return _x;}
    public int getY() {return _y;}
    public void move(int x, int y) {
        this._x = x;
        this._y = y;
    }
}   


class B extends A {
    private String _color;
    public B(int x, int y, String color) {
        super(x, y);
        this._color = color;
    }
    // i try to invoke the method of super-class inside the sub-class
    public void setXY(int x, int y) {
        super.move(x, y);
    }
    public void setColor(String color) {
        this._color = color;
    }

    public static void main(String[] args) {
        B b = new B(5, 5, "Yellow");
        
        // when I compile this code, I got the@4759e894 as the result.
        b.setXY(10, 20);
        b.setColor("Red");
        String str = b.toString();
        System.out.println(str);
        
    }
}


标签: javaoopinheritance

解决方案


推荐阅读