-1

So I'm very new to programming and just trying to instantiate a class in another class, but i keep getting an error that says: Cannot Resolve Symbol. Could someone tell me which area the problem lies in?

My First Class looks like this:

public class Triangle
{
    public static void main(String[] args)
    {
    }
    public static void Draw (int num)
    {
        System.out.print("*");
    }
}

The second looks like this:

public class Lab01
{
    public static void main(String[] args)
    {
           Triangle obj2 = new Triangle.Draw(5);
    }
}

Thanks in advance

code_dredd
  • 5,915
  • 1
  • 25
  • 53

2 Answers2

1

There're at least 2 issues:

  1. The first is that a program must have only one main function. Yours here has two. The main function in your Triangle class should be removed.

  2. The other issue is that, to actually instantiate a class, you need to invoke the class' constructor with the new operator, but your Triangle obj2 = new Triangle.Draw(5); line does not do this. Instead, it tries to use a static void method, which does not instantiate or return anything.

You should consider changing your Triangle as follows:

public class Triangle
{
    public Triangle() {
        System.out.println("Constructing triangle instance");
    }

    public void draw() {
        System.out.println("Drawing triangle instance");
    }
}

// using the class
Triangle t = new Triangle();
t.draw();

This gives you a public default constructor and also a non-static draw method that should take care of drawing the specific instance you've created.

code_dredd
  • 5,915
  • 1
  • 25
  • 53
0

You need to instantiate your Triangle object

//remove the static modifier if using below
Triangle obj2 = new Triangle();
obj2.draw(5);


//since your method is static you can just call it from the class also.
Triangle.draw(5);

What you were doing was trying to assign the return value from Triangle.draw() to your Triangle object. Since draw is void and does not return a Triangle type, it throws the error.

Here is a good stackoverflow post that shows a great example of when to use static methods.

Community
  • 1
  • 1
Ryan
  • 1,972
  • 2
  • 23
  • 36
  • Trying to access static methods from instances is bad practice and also generates warnings: `The static method Draw() from the type Triangle should be accessed in a static way` – code_dredd Jan 05 '16 at 04:29
  • Which is why I provided two options, one for removing the static modifier and instantazing and another for accessing the draw method in static context – Ryan Jan 05 '16 at 04:31