Java 如何在下面的代码中正确使用toString方法?

Java 如何在下面的代码中正确使用toString方法?,java,tostring,Java,Tostring,我想在我的程序中使用tostring()方法以以下方式打印赋值: class employee { double b; } class manager extends employee { } public class employeestockplan { static Object o; public void agrantstock() { if(o instanceof manager) { ((em

我想在我的程序中使用
tostring()
方法以以下方式打印赋值:

class employee
{
    double b;
}
class manager extends employee
{
}
public class employeestockplan
{
    static Object o;
    public void agrantstock()
    {
        if(o instanceof manager)
        {
            ((employee) o).b = 80000;
        }
        else if(o instanceof employee)
        {
            ((employee) o).b  = 50000;
        }
    }

    public String toString()
    {
        return ((employee) o).b+" ";
    }
    public static void main(String[] args)
    {
        o = new employee();
        employeestockplan t = new employeestockplan();
        System.out.println(t);
    }
}

但是输出是
0.0
,我应该在哪里修改我的程序?我个人认为我在指定o是否是员工或经理的对象时犯了错误,或者将
toString
方法放错了位置,但我不确定。

您需要在类
employeestockplan
中重写方法
toString
,这里您拼写错误,它不是
tostring
,而是
tostring
。是的,Java区分大小写

响应更新:

50000.0 
您从未在当前代码中调用过
agrantstock()
,这就是您得到0的原因。试试这个:

employeestockplan.o = new employee();
employeestockplan t = new employeestockplan();
t.agrantstock();
System.out.println(t);
输出:

50000.0 

NB:
o
应为
员工
类型,而不是
对象
,这将大大简化您的代码,您应该在
employee
中实现一个方法
agrantstock
,并在
manager
中重写它,这样您就不再需要用instanceof测试类型了。

这是因为您从未调用将值赋给b的agrantstock()方法

通过将静态属性设置为Employee而不是对象,可以简化该方法。下面是您的代码的一个稍加修改的版本,也修改为遵循标准命名约定:

class Employee {
    double b;
}

class Manager extends Employee {
}

public class EmployeeStockPlan {

    static Employee employee;

    public void grantStock() {
        if (employee instanceof Manager) {
            employee.b = 80000;
        } else {
            employee.b = 50000;
        }
    }

    public String toString() {
        return ((Employee) employee).b + " ";
    }

    public static void main(String[] args) {
        employee = new Employee();
        EmployeeStockPlan stockPlan = new EmployeeStockPlan();
        stockPlan.grantStock();
        System.out.println(stockPlan);
    }
}

请注意在main方法中添加了stockPlan.grantStock()

使用正确的名称-
toString()
oop这是我的错误,但是它也会产生另一个不需要的输出…这是0.0您没有调用
agrantstock()
anywhere,因此
employee
对象中
b
的值仍然是
0.0
。打印
t
之前,请调用
agrantstock()