Click here to Skip to main content
15,896,445 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I saw many programs containing objects but in all of them object was declared in static method. So, I have a following doubt.

How to use the objects which are not defined in static methods ?
Can you provide me a example in which object is defined outside static method ?

What I have tried:

go through some random articles
Posted
Updated 25-Dec-20 21:02pm

That's because you are looking at trivial examples: every Java application must contain a main method whose signature looks like this:
Java
public static void main(String[] args)
It is required to be static because its the starting point, and it is not associated with any object instance.

And once you get beyond "Hello World!" apps, the first thing most main functions do is create an instance of a class and start working with it. From that point on, static functions become rarer, the are only used in special cases.
Java
public class Main {
	public static void main(String[] args) {
		System.out.println("Initializing...");
		Main m = new Main();
		m.Run();
	}
	public Main() {
	    
	}
	public void Run(){
	    System.out.println("Running ...");
	    ...
	}
}
The Run method will create loads of instances of different classes to do what it requires.
 
Share this answer
 
See the Objects & Classes chapter in this online tutorial:
online-resources-for-learning-java~tutorialspoint-java-tutorial[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900