简体   繁体   English

在对象上调用方法 Java

[英]Calling methods on objects Java

I'm taking an introduction to java programming course at university and have an exam next week.我正在大学介绍java编程课程,下周要考试。 I'm going through past exam papers am sort of stuck on this question:我正在浏览过去的试卷,我有点困在这个问题上:

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] 

I've included my code below, but what i'm stuck on is in the final part to this question.我在下面包含了我的代码,但我在这个问题的最后一部分被困住了。 How does one call a method on a new object (as we haven't been taught that in class)?如何在新对象上调用方法(因为我们在课堂上没有学过)? Or, does the question imply that the method has to be usable with any object, not just the created object?或者,问题是否意味着该方法必须可用于任何对象,而不仅仅是创建的对象?

Sorry for my awful code and dumb question, i'm really struggling with Java.对不起,我糟糕的代码和愚蠢的问题,我真的在用 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));


 }
}

You're very close to the solution.你非常接近解决方案。 Simply make a method like this:简单地做一个这样的方法:

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

Then you can call it in your main method like this:然后你可以像这样在你的主方法中调用它:

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

NB: remove the semicolon at the end of public static void main(String[] args) {;注意:删除public static void main(String[] args) {;末尾的分号

I think you were meant to create a non-static method named out , which can be called by the client of the class (any place where you create a new object of type X ) using the dot notation我认为您打算创建一个名为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