Search code examples
javainstantiation

How to instantiate an object in 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);
    }
}

Solution

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

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

    But that doesn't really make sense, your Sample method always returns 3 .

    Are you trying to do something like this :

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