簡體   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