如何在java中实例化一个对象?
我是编程新手,我想知道在实例化对象时我出了什么问题。 以下是代码:
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 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); } }
我怀疑你真的想要创建一个对象。
从您的代码片段中,我了解您要运行一个名为Sample
的’方法’,它会添加两个数字。 在JAVA中,您不必实例化方法。 对象是class
实例。 方法只是这个类所具有的行为。
根据您的要求,您不需要显式实例化任何内容,因为当您运行已编译的代码时,JAVA会自动创建类的实例并在其中查找要执行的main()
方法。
您可能只想做以下事情:
public class Testing{ private int sample(int a, int b) { return a + b; } public static void main(String[] args) { int c = sample(1, 2); System.out.println(c); } }
注意:我将Sample
更改为sample
,因为通常接受的做法是使用带有小写字母的小写和类名启动方法名称,因此在该方面Testing
是正确的。
您使用new
关键字正确实例化,但您的calss名称和方法调用是错误的
Testing myTest = new Testing(); int result =myTest.Sample(1); //pass any integer value System.out.println(result );
Sample不是一个类,它只是一个方法。 您无法创建它的实例。 你只运行它 –
int sample = Sample(3);
如果您希望将样本作为类,请将其定义为类。
在您的情况下,该方法不是静态的,因此您无法从Static方法Main直接访问它。 使其静止,以便您可以访问它。 或者只是创建一个新的测试实例并使用它 –
Testing testing = new Testing(); int sample = testing.Sample(3);
Sample方法返回integer,因此获取结果并在任何地方使用它。
public static void main(String []args) { int myTest = Sample(4555);//input may be any int else System.out.println(myTest); }
这就是你应该这样做的方式。
public class Testing{ public int Sample(int c) { int a = 1; int b = 2; c = a + b; return c; } public static void main(String []args) { // Creating an Instance of Testing Class Testing myTest = new Testing(); int c =0; // Invoking the Sample() function of the Testing Class System.out.println(myTest.Sample(c)); }