gpt4 book ai didi

java - 如何在java中实例化一个对象?

转载 作者:搜寻专家 更新时间:2023-10-30 21:42:55 24 4
gpt4 key购买 nike

我是编程新手,我想知道我在实例化对象时哪里出错了。下面是代码:

public class Testing{
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
Sample myTest = new Sample();
System.out.println(c);
}
}

最佳答案

您的代码中没有Sample 类。您声明的方法是私有(private)方法。

// private method which takes an int as parameter and returns another int
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}

对于当前代码段,您需要实例化 Testing 类并使用 Sample 方法。请注意您的类定义前面有关键字 class ,在本例中为 class Testing

public class Testing{
private int Sample(int c)
{
int a = 1;
int b = 2;
c = a + b;
return c;
}
public static void main(String []args)
{
Testing t = new Testing(); // instantiate a Testing class object
int result = t.Sample(1); // use the instance t to invoke a method on it
System.out.println(result);
}
}

但这并没有真正意义,您的 Sample 方法总是返回 3

你是不是想做这样的事情:

class Sample {
int a;
int b;

Sample(int a, int b) {
this.a = a;
this.b = b;
}

public int sum() {
return a + b;
}
}

public class Testing {
public static void main(String[] args) {
Sample myTest = new Sample(1, 2);
int sum = myTest.sum();
System.out.println(sum);
}
}

关于java - 如何在java中实例化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com