【问题标题】:Java get for two different methodJava获取两种不同的方法
【发布时间】:2021-10-25 20:10:03
【问题描述】:

谁能帮忙,如何正确实现下一个任务:我在类中有两个不同的方法和一个 get() 来返回这个方法的结果。例如:

public class MyClass {
    
    private String Data1;
    private String Data2;
    
    public void Method1() {
        this.Data1 = "111";
    }
    
    public void Method2() {
        this.Data1 = "222";
    }
    
}

然后我打电话

new MyClass ().Method1().get() //Expect to get 111
new MyClass ().Method2().get() //Expect to get 222

以及如何创建这个get方法?谢谢!

【问题讨论】:

  • 我不确定我是否理解您的问题。你能自己再读一遍吗? Method1Method2 返回 void.. 你不能在 void.. 上调用任何东西,而且 - 你似乎没有在任何地方定义 get()

标签: java class methods


【解决方案1】:

我不知道你想实现什么,但 Java 中最接近 POO 模式的东西是这样的:

public class MyClass {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Sub obj_sub = new Sub();
        System.out.println("value of Data1: " + obj_sub.getData1());
        System.out.println("value of Data2: " + obj_sub.getData1());
    }

    public static class Sub {
        private String Data1, Data2;
        public Sub() {
            super();
            setData1("111");
            setData2("222");
        }
        public String getData1() {
            return Data1;
        }
        public void setData1(String data1) {
            Data1 = data1;
        }
        public String getData2() {
            return Data2;
        }
        public void setData2(String data2) {
            Data2 = data2;
        }
    }
}

【讨论】:

    【解决方案2】:

    我认为你需要这样的东西:

    public class MyClass {
        public static void main(String[] args) {
            MyClass myclass = new MyClass();
            myclass.Method1();
            myclass.Method2();
    
        }
        
        private String Data1;
        private String Data2;
    
        public void Method1()
        {
            this.Data1 = "111";
            System.out.println(Data1);
        }
    
        public void Method2()
        {
            this.Data2 = "222";
            System.out.println(Data2);
        }
    
    
    }
    

    初始化类对象为MyClass myclass = new MyClass(); 调用方法

    myclass.Method1();
    myclass.Method2();
    

    在此处使用官方 Java 文档了解有关此关键字的更多信息:https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

    【讨论】:

      猜你喜欢
      • 2017-03-01
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 2016-11-12
      • 2019-08-23
      • 1970-01-01
      相关资源
      最近更新 更多