public class ScopeExam{
int globalScope = 10;
// 인스턴스 변수 . 클래스의 속성으로 선언
public void scopeTest(int val){
int localScope = 10;
// 속성으로 선언되어 클래스 전체 scope
System.out.println(globalScope);
System.out.println(localScpe);
System.out.println(val);
}
public void scopeTest2(int val2){ System.out.println(globalScope);
System.out.println(localScpe);// localscope는 scopeTest의 속성이으로 scopeTest2에서는 사용이 불가하다.
System.out.println(val);// localscope는 scopeTest의 파라미터이으로 scopeTest2에서는 사용이 불가하다.
}
public static void main(String[] args) {
System.out.println(globalScope); //오류
System.out.println(localScope); //오류
System.out.println(value); //오류
}
static
public class VariableScopeExam {
int globalScope = 10;
static int staticVal = 7;
public void scopeTest(int value){
int localScope = 20;
}
public static void main(String[] args) {
System.out.println(staticVal); //사용가능
}
}
1) static : 클래스의 객체 생성 없이 접근
2) public : 객체에만 접근
1) Static (정적)
2) public
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
(W3school: https://www.w3schools.com/java/java_class_methods.asp)