繁体   English   中英

在对象上调用方法 Java

[英]Calling methods on objects Java

我正在大学介绍java编程课程,下周要考试。 我正在浏览过去的试卷,我有点困在这个问题上:

Consider the following class X: class X { private boolean a; private int b; ... } 

(i)     Write a constructor for this class. [2 marks] 


(ii)   Show how to create an object of this class. [2 marks] 


(iii)  Add a method out, which returns b if a is true, and -b otherwise. This method must be usable for any client of 
    this class. [2 marks] 

我在下面包含了我的代码,但我在这个问题的最后一部分被困住了。 如何在新对象上调用方法(因为我们在课堂上没有学过)? 或者,问题是否意味着该方法必须可用于任何对象,而不仅仅是创建的对象?

对不起,我糟糕的代码和愚蠢的问题,我真的在用 Java 苦苦挣扎。

public class X {
 private boolean  a;
 private int b;

 X(final boolean i, final int j) {
  a = i;
  b = j;

 }

 static int Out(boolean a, int b) {
 if (a == true) {
  return b;
 }
  return -b;
 }

 public static void main(String[] args) {;

 X object1 = new X(true, 5);

 System.out.println(Out(object1));


 }
}

你非常接近解决方案。 简单地做一个这样的方法:

public int out() {
    if (a) {
        return b;
    } else {
        return -b;
    }
}

然后你可以像这样在你的主方法中调用它:

X object1 = new X(true, 5);
System.out.println(object1.out());

注意:删除public static void main(String[] args) {;末尾的分号

我认为您打算创建一个名为out的非静态方法,该方法可以由类的客户端(在您创建X类型的新对象的任何地方)使用点表示法调用

public int out() {
   if(a)
      return b;
   else
      return -b;
}

public static void main(String[] args) {
   X object1 = new X(true, 5);
   int result = object1.out();
   System.out.println(result);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM