如何在java中实例化一个对象? [英] How to instantiate an object in java?

查看:105
本文介绍了如何在java中实例化一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,我想知道在实例化对象时我出了什么问题。下面是代码:

I'm new in programming and I would like to know where did I go wrong in instantiating an object. Below is the code:

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);
    }
}


推荐答案

那里您的代码中没有示例类。你声明的那个是私有方法。

There is no Sample class in your code . The one which you have declared is a private method .

// 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;
}

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

With the current snippet , You need to instantiate the Testing class and make use of the Sample method. Notice your class definition is preceded by the keyword class , in this case 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);
 }
}

但这不是真的有意义,你的示例方法始终返回 3

But that doesn't really make sense, your Sample method always returns 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中实例化一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆