1 public class C {You can't invoke an instance method or instance variables from a static method since non static method/variables cannot be referenced from a static context.. You can invoke a static method or reference a static variable from an instance method? c is an instance variable, which cannot be accessed from the static context in method2.
2 public static void main(String[] args) {
3 method1();
4 }
5
6 public void method1() {
7 method2();
8 }
9
10 public static void method2() {
11 System.out.println("What is radius " + c.getRadius());
12 }
13
14 Circle c = new Circle();
15 }
For an example:
However, you can invoke a static method or reference a static variable from an instance method Because static can be used without any instance of the class.
About what is wrong in provided code, at line 3, cannot invoke non-static method method1() without create an instance of classC and at line 11,method getRadius() haven't been defined, method getRadius() can't find.
Remarks
Text provided above does not means is the model answer, and it's was posted here for an reference to somebody who interested the related knowledge only. if there is something incorrect, please leave a comment so that i can correct it or for others viewer to have an better reference, if you want know more about this topic and where is the question, concept or answer from, you can reference from information provided under the reference sub-title.
Reference:
1) Introduction to Java Programming, Y. Daniel Liang 9.19
2) http://stackoverflow.com/questions/21397108/why-cant-a-static-method-refer-to-an-instance-method
No comments :
Post a Comment