public class InstanceMethodTest
{
int instanceVar = 10;
static String staticVar = "Welcome";
/*
* Instance methods can access instance variables and instance methods
* directly.
*
* Instance methods can access class variables and class methods directly.
*/
public void instanceMethod1()
{
System.out.println("instanceMethod1 is called.");
System.out.println("instanceVar : " + instanceVar);
instanceMethod2();
System.out.println("staticVar : " + staticVar);
staticMethod();
}
public void instanceMethod2()
{
System.out.println("instanceMethod2 is called.");
}
public static void staticMethod()
{
System.out.println("staticMethod is called.");
}
}
ClassMethodTest.java public class ClassMethodTest
{
int instanceVar = 10;
static String staticVar = "Welcome";
public void instanceMethod1()
{
System.out.println("instanceMethod1 is called.");
}
/*
* Class methods can access class variables and class methods directly.
*
* Class methods cannot access instance variables or instance methods
* directly—they must use an object reference. Also, class methods cannot
* use the this keyword as there is no instance for this to refer to.
*/
public static void staticMethod()
{
System.out.println("staticMethod is called.");
System.out.println("staticVar : " + staticVar);
staticMethod();
System.out.println("instanceVar : " + instanceVar);
instanceMethod1();
System.out.println(this.instanceVar);
ClassMethodTest classMethodTest = new ClassMethodTest();
System.out.println("instanceVar : " + classMethodTest.instanceVar);
classMethodTest.instanceMethod1();
}
}