static vs non static java code example

Example 1: can you run non static method on main

//You simply need to create an instance of the Object you created
public Class Obj{
	public void nonStaticMethod(){
	//execute code
	}
	public static void main(string args[]){
		Obj obj = new Obj();
	    obj.nonStaticMethod
	}
}

Example 2: static vs non static java

// Static vs Object Called
// Static Methods don't require you to call a constructor

// Initialize statically
public class MyClass {

  private static int myInt;

  static {
      myInt = 1;
  }

  public static int getInt() {
      return myInt;
  }
}

// Then call it
System.out.println(MyClass.getInt());

// VS Constructor

public class MyClass {
 
  private int myInt;
  
  public MyClass() {
    myInt = 1;
  }
  
  public int getInt() {
	return this.myInt;
  }
}
// Then call it
MyClass myObj = new MyClass();
System.out.println(myObj.getInt());

Tags:

Java Example