Thursday, 19 May 2016

Static methods access only static members and methods

check below class1 & class2 as follows.

public class Class1 {

public int myNumber = 799;

private void method(){
System.out.println("Hi i am private method");
}

public void method1(){
System.out.println("Hi i am public method1");
}
}

public class Class2 extends Class1{

public static void main(String args[]) {
Class2 obj = new Class2();
obj.method2();
}


public void method2() {
method1();
System.out.println("my num : "+myNumber);
}

}

Here class1 is super class and class2 is sub class. if you want to call method1 of class1 in main of class2, the method of class1 is must be a static. otherwise it shows the error. without using static, i create object of given class and call method2. in method2 contains methods of class1. in this way we will call methods in static mehods without using static.

No comments:

Post a Comment