私はプログラミングの初心者なのですが、オブジェクトのインスタンス化でどこが間違っているのか知りたいのです。以下はそのコードです。
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 があることに注意してください。
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);
}
}
実際にオブジェクトを作成したいとは思いません。
コードスニペットから、2つの数値を追加する「サンプル」という名前の「メソッド」を実行することを理解しています。 そして、JAVAでは、メソッドをインスタンス化する必要はありません。 オブジェクトは「クラス」のインスタンスです。 メソッドは、このクラスが持つ動作にすぎません。
要件については、コンパイルされたコードを実行するときに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はクラスではなく、単なるメソッドです。インスタンスを作成することはできません。 実行するだけです。
int sample = Sample(3);
sample をクラスとして定義したい場合は、クラスとして定義します。
あなたの場合、メソッドが static でないため、Static メソッド Main から直接アクセスすることができません。staticにすることでアクセスできるようになります。もしくは、Testingのインスタンスを新規に作成して、それを使用する -。
Testing testing = new Testing();
int sample = testing.Sample(3);
これがあなたがこれを行うべき方法です。
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));
}