백 엔드/java

자바:Java(2)

까르르꿍꿍 2021. 10. 26. 16:20

자바는 객체지향 언어이다.

객체지향이란 하나의 사물을 하나의 클래스로 설명하는 언어이다.

사물에 대한 설명은 그 물체의 상태(필드)와 행동(메서드)로 나눌 수 있다.

 

1.메서드는 리턴형 유무나 매개변수 유무 등에 따라 다양한 형태로 정의할 수 있다.

pakage javastudy;

public class MyClass{
	public void method1(){
  		System.out.println("m1이 실행됨...");
    }
    public void method1(int x){
   		System.out.println(x+"m1이 실행됨...");
    }
    public int method1(){
 		System.out.println("m1이 실행됨...");
        return 10;
    }
    public void method1(int y){
 		System.out.println(y+"m1이 실행됨...");
        return y;
    }
}

 메서드를 사용하기 위해서 주의해야할 점은 먼저 객체를 만들어야한다.

package javastudy;

public class MyclassExam{

	public static void main(String[] args){
    	MyClass myclass = new MyClass();
        myclass.method1();
        myclass.method2(10);
        myclass.method3();
        int value=myclass.method3();
        System.out.println("m3가 리턴한 값"+value);
    }
}

2.static한 메서드

static한 메서드는 객체를 생성하지 않아도 static한 메서드나 static한 벼누를 사용할 수있지만 static하지 않은 것은 사용할 수 없다.static하지 않은 것들을 사용하기 위해서는 객체를 사용해야한다.

또 static변수는 참조변수라 값을 공유한다. 

public class VariableScopeExam{
	int globalScope=10;
    static int staticVal=7;
    
    public void scopeText(int value){
    	int localScope=20;
        
        System.out.println(globalScope);
        System.out.println(localScope);
        System.out.println(value);
    }
    public void scopeText2(int value){
        System.out.println(globalScope);
        System.out.println(localScope); //컴파일 에러 이유는 localscope는 scopeText에서 선언되어서 여기는 적용 안됨
        System.out.println(value);//컴파일 에러 같은이유
        System.out.println(value2);
    }
    
    public static void main(String[] args){
    	System.out.println(staticVal);
        VariableScopeExam v1=new VariableScopeExam();
        System.out.println(v1.globalScope);
        VariableScopeExam v2=new VariableScopeExam();
        v1.globalScope=10;
        v2.globalScope=10;
        System.out.println(v1.globalScope);
        System.out.println(v2.globalScope);
        v1.staticVal=50;
        v2.staticVal=100;
        System.out.println(v1.staticVal);// 100출력 static변수는 공유하기 때문에 v1이든v2든 값공유
        System.out.println(v2.staticVal);//100출력
    }
}

열거형(enum):서로 관련 있는 상수들을 모아서 집합으로 정의한 것

package javaStudy;

public class EnumExam {
	public static final String MALE="MALE";
	public static final String FEMALE ="FEMALE";
	public static void main(String[] args) {
		String gender1;
		gender1=EnumExam.MALE;
		gender1=EnumExam.FEMALE;
		
		Gender gender2;  //enum형 열거형
		gender2=Gender.MALE;
		gender2=Gender.FEMALE;
	}
}
enum Gender{
	MALE,FEMALE;
}