1

Can a main() be accessed directly from outside the class in which it is defined? Like for example:

class B { main(); } class A { public static void main(String arg[]) { int a=10; int b=20; System.out.println(a+" "+b); } } 
14
  • Let's assume that the code could actually compile, in order to call main from class B, you would need an instance of B, something like B b = new B();, then you can use b to call main, something like b.main(); Commented Jan 23, 2017 at 5:23
  • You might like to have a closer look at Defining Methods and the associated tutorials for more information Commented Jan 23, 2017 at 5:24
  • @MadProgrammer Yes. I could do that but as main() has a public modifier and is in class A, I thought of if it could only be directly accessed from within the same class or also from outside the class. Commented Jan 23, 2017 at 5:27
  • 2
    You wouldn't need an instance of class A to call A.main because main is a static method. Commented Jan 23, 2017 at 5:28
  • @BIJAY I'm probably misinterpreting the question, you might like to clarify it more Commented Jan 23, 2017 at 5:29

1 Answer 1

1

You can call main method from other class as well because its static.no object reference is require to call static method, but you should call it from other method like below.

public class B { public static void main(String[] args) { String[] s = {"a"}; A.main(s); } } class A { public static void main(String arg[]) { int a=10; int b=20; System.out.println(a+" "+b); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.