I am not able to figure out what's wrong with the following code:
Is it a rule to create objects in class that contains main method and then use this object to access the methods?
I did exactly reverse in the following code and i am not able to compile it.

class Twoclass
{
    Oneclass obj1=new Oneclass();
    obj1.show();
}


public class Oneclass
{
  public static void main(String args[])
    {
        System.out.println("Hallowee");
    }
   public void show()
   {
    System.out.println("howjk");
   }
}


 obj1.show();
It is giving the errror as identifier expected on line  obj1.show();

Recommended Answers

All 5 Replies

It is giving the errror

Please copy and post the full text of the error message.

Not sure what "rule" you are talking about. There is a rule that the class that you start the program execution with using the java command must have a main() method.

Yes. Take the Main method out of Oneclass and put it in Twoclass and it should work as intended.

Also don't forget to use standard naming conventions for class names.

use standard naming conventions

Take the Main method
vs main()

You have that error message because you out an executable statement that's not in a method. Executable statements need to be in a method or constructor. That could be main, or any other method that gets called directly or indirectly from main (including constructors).

(Ps: for the experts out there, I'm deliberately ignoring static and instance initialisers as being too advanced to be relevant)

@Starstreak: yes i know that it would work that way.What i was asking was , why the code that i wrote was not working?

@JamesCherill: yes i got what you are saying.Now the code works fine.Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.