Java OOP问题举例。寻求帮助

时间:2014-08-27 03:44:12

标签: java class oop

我对我遇到的情况有疑问。我写了一个非常基本的程序来帮助向您展示我的问题的一个例子。我想知道(如果可能的话)以某种方式做某事。它涉及一个类的变量,另一个类的方法。并将它们一起用于在Main中获得结果。

主:

// The main, which creates an object of Testing and Yupp, then Tries to run the method to add +3 and display it, repeatidly.

import javax.swing.JOptionPane;

public class Runit
{

    public static void main(String[] args)
    {
        Testing testing = new Testing();
        Yupp yupp = new Yupp();

        JOptionPane.showMessageDialog(null, testing.number);
        yupp.doMath();
        JOptionPane.showMessageDialog(null, testing.number);
        yupp.doMath();
        JOptionPane.showMessageDialog(null, testing.number);
        yupp.doMath();
        JOptionPane.showMessageDialog(null, testing.number);
        yupp.doMath();
        JOptionPane.showMessageDialog(null, testing.number);
    }

}

Yupp班:

//Just extending all the information from Testing class( which holds the "number" variable so I have access to it ) Then making the simple personal method to add 3 to it.

public class Yupp extends Testing
{

    public void doMath()
    {
        number = number + 3;
    }

}

测试类:

// Just holding the number variable in this class.


public class Testing
{
    int number = 3;
}

基本上我想要发生的事情,无论它是否正确编码,我都确定它不是。 应该(我想要)发生的是"数字"变量,应该在每个单独的JOptionPane窗口上增加3。就像我说的,它只是我写的一个基本代码示例来解释我的问题。我认为这种方式很有意义。谢谢你,如果你能帮我弄清楚如何做到这一点。

目前这个号码总是以3.而不是3 + 3,6 + 3,9 + 3等。

2 个答案:

答案 0 :(得分:4)

<强>问题:

testing.number

您从Testing的实例获得的数字与增加的数字相同,因此总是为您提供3

<强>溶液

使用您的Yupp对象从方法调用doMath获取增量值

<强>样品:

    JOptionPane.showMessageDialog(null, yupp.number);
    yupp.doMath();
    JOptionPane.showMessageDialog(null, yupp.number);
    yupp.doMath();
    JOptionPane.showMessageDialog(null, yupp.number);
    yupp.doMath();
    JOptionPane.showMessageDialog(null, yupp.number);
    yupp.doMath();
    JOptionPane.showMessageDialog(null, yupp.number);

答案 1 :(得分:4)

简而言之:

您正在创建两个不同的对象:

Testing testing = new Testing();
Yupp yupp = new Yupp();

然后,您在一个(doMath)中调用操作(yupp),但打印另一个(number)的属性testing。最后一个,在整个程序中没有变化。