-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstance method.java
51 lines (41 loc) · 1017 Bytes
/
Instance method.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Accessing without object:
class Main
{
int instanceVar=42;
public void displayInstanceVar(){
System.out.println("Instance Variable: "+instanceVar);
}
public void greet(){
System.out.println("Hello from greet method!");
displayInstanceVar();
}
public static void main(String[] args) {
greet();
}
}
output:
Main.java:15: error: non-static method greet() cannot be referenced from a static context
greet();
^
1 error
Accessing with object:
class Main
{
int instanceVar=42;
public void displayInstanceVar(){
System.out.println("Instance Variable: "+instanceVar);
}
public void greet(){
System.out.println("Hello from greet method!");
displayInstanceVar();
}
public static void main(String[] args) {
Main d = new Main();
d.displayInstanceVar();
d.greet();
}
}
output:
Instance Variable: 42
Hello from greet method!
Instance Variable: 42