简体   繁体   English

吸气剂和吸气剂

[英]Getters and Setters

So, I have written a code that is supposed to take two ints -f and s (first and second) - and return the sum.所以,我编写了一个代码,它应该采用两个整数 -f 和 s(第一个和第二个) - 并返回总和。 Eclipse didn't really like what I was doing, so I changed my code and added some getters and setters - which I am very unfamiliar with. Eclipse 不太喜欢我正在做的事情,所以我更改了我的代码并添加了一些 getter 和 setter - 我非常不熟悉这些。 I got Eclipse to create my getters and setters.我让 Eclipse 来创建我的 getter 和 setter。 My code still doesn't work, but I don't really know why.我的代码仍然不起作用,但我真的不知道为什么。

Here it is:这里是:

public class Main extends Comp{

    public static void main(String[] args){
        Comp.give(getF(), getS());
    }
}




import java.util.Scanner;
//Feel the rhythm
//Feel the rhyme
//Come on Eclipse
//It's coding time!!!
public class Comp {
    private int f;
    private int s;
public void look(){
    Scanner iscan = new Scanner(System.in);
        setF(iscan.nextInt());
        setS(iscan.nextInt());
        iscan.close();  

}
public static void give(int f, int s) {
    System.out.println(f+s);

    }
public int getS() {
    return s;
}
public void setS(int s) {
    this.s = s;
}
public int getF() {
    return f;
}
public void setF(int f) {
    this.f = f;
}


}

The Problem - Eclipse has underlined getF(), getS() (Main method only) in red.问题 - Eclipse 已用红色下划线 getF()、getS()(仅限 Main 方法)。 When I hover over it, it says change getF() to static [same for getS()], but I don't want it to be static.当我将鼠标悬停在它上面时,它说将 getF() 更改为静态 [getS() 相同],但我不希望它是静态的。

It also used this.f and this.f.它还使用了 this.f 和 this.f。 I kinda know what that means, but not too well.我有点知道这意味着什么,但不太清楚。 An explanation of that would be great.对此的解释会很棒。

this.f refers to the instance variable f in your Comp class. this.f指的是Comp类中的实例变量f Since the parameter for setF(int f) is also called f , the this helps distinguish between the two.由于setF(int f)的参数也称为fthis有助于区分两者。 It's basically saying "assign the method parameter f to my instance variable f ".它基本上是在说“将方法参数f分配给我的实例变量f ”。

As for the error, you'd either need to make getF() and getS() static, or create an instance of your Comp class in main and call the two methods using that:至于错误,您需要将getF()getS()静态,或者在main创建Comp类的实例并使用它调用这两个方法:

public static void main(String[] args){
    Comp comp = new Comp();
    Comp.give(comp.getF(), comp.getS());
}

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

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