본문 바로가기

school of computing/Object-Oriented programming

JAVA | Ch02. Java의 Class와 Methods

Java는 객체(object)로 구성되어져 있다. 이때 Object는 class type의 변수라고도 할 수 있다. Object는 data를 가지고 method로 정의된 행동을 한다. 

 

Class는 실제 Object를 어떻게 만들지 정의하는 설계도 이다. 여러 객체의 공통성을 모으고 요약하여 Abstraction(추상화)를 하여 만들어낸다. 그래서 Class를 붕어빵 틀이라고 생각하면 쉽다. 붕어빵 틀인 Class를 가지고 여러 붕어빵을 찍어내는데 이때 붕어빵 하나하나가 Object(객체) 이다. 그래서 Object는 Class의 instance라고 한다. 또한 class는 data를 가지지 않고 각각의 object가 data를 가질 수 있다. (꼭 그런것 이 아닌게 static으로 선언 했을때 전역 변수처럼 사용하여 하나의 class차원의 data를 가질 수 있다.) Class내에 main이 들어간 class는 library로 사용할 수 없기 때문에 다른 class에서 불러와 사용 할 수 없다.

 

코드를 보며 이해해보자.

public class Dog {
    public String name;
    public String breed;
    public int age;

    public void writeOutput() {

        System.out.println("Name: " + this.name);
        System.out.println("Breed " + this.breed);
        System.out.println("Age in calendar years: " + this.age);
        System.out.println("Age in human years : " +  this.getAgeInHumanYears());
        System.out.println();
    }
    
    public int  getAgeInHumanYears(){

        int humanAge = 0;
        if (age <=2){
            humanAge = age *11;
        }
        else {
            humanAge = 22 + ((age-2)*5);
        }
        return humanAge;
    }

}

위 Dog Class는 개의 name, breed, age를 저장하고 writeOutput, getAgeInHumanYears Method로 정의된 행동을 한다.

이 data item과 method는 객체에 속해 있기 때문에 객체의 members라고 불리고 class내에서 정의된 data(name, breed, age)는 instance variable라고 불린다. 

 

instance variable을 선언할때 자료형 앞 public은 이 instance variable이 어떻게 사용되든 제한이 없다는 것을 의미한다. 다른 class에서 객체를 생성하여 직접 이 instance variable에 접근 할 수 있는것이 public이다. 반대로 private로 선언하면 다른 class에서 직접 접근할 수 없고 오직 해당 class의 method로만 접근할 수 있다. 

 

Dog class를 실행하기 위해 DogDemo class를 만들어준다.

public class DogDemo {
    public static void main(String[] args) {

        Dog balto = new Dog();
        
        balto.name = "Balto";
        balto.age = 8;
        balto.breed = "Siberian Husky";
        balto.writeOutput();

        Dog scooby = new Dog();
        
        scooby.name = "Scooby";
        scooby.age = 42;
        scooby.breed = "Great Dane";
        
        System.out.println(scooby.name + " is a " + scooby.breed + ".");
        System.out.print("He is " + scooby.age + " years old, or ");
        int humanYears = scooby.getAgeInHumanYears();
        System.out.println(humanYears + " in human years.");
    }
}

DogDemo의 Output

Dog타입의 object를 두개 생성해주고 이름을 각각 balto , scooby라고 선언했다.

: Dog balto = new Dog();

 

객체의 instance variable에 값을 넣기 위해 object name. instance variable's name을 적어 접근했다.

: balto.name = "Balto";

 

이때 왜 new를 사용할까? 

new를 사용하는 이유는 java에서 class의 객체를 새로 생성하기 위해 사용한다. new를 했을 때만 object의 공간이 메모리에 할당되고 이때 object의 이름은 생성된 객체의 aderess를 저장한다. 그래서 new를 했을 때 object가 새로 생성될 때마다 새로운 instance variable을 둔다. 비로소 new를 했을대 메인 메모리에 공간이 할당된다.

 

method에는 두가지 종류가 있는데 value값을 return하는 method, 아무것도 return하지 않는 (void)method가 있다. Java에서는 return한다는 것을 produce한다고 한다. 즉, method는 다른 프로그램에서 값을 사용하고 행동을 수행하기 위해 값을 "produce"한다. 다른 class에서 객체의 method를 사용할 때 method를 "invoke"한다고 말한다. DogDemo class에서 balto객체를 생성하고 wirteOutput() method를 사용한 것이 invoke한 것이다. 또한 method는 다른 class에서도 사용할 수 있도록 주로 public으로 선언된다.

 

이때 writeOutput() method는 return값이 없기 때문에 아무것도 return 하지 않는 void method이다.

: balto.writeOutput();

->이를 Dog class에서 method를 정의 할 때 아무것도 return하지 않도록 void형으로 정의 해준다.

: public void writeOutput() {...}

 

반면 getAgeInHumanYears() method는 int형의 값을 return하기 때문에 값을 저장해주는 변수 또한 필요하다. 그래서 새로운 변수 humanYears를 int형으로 선언해 준 후 return값을 넣어준다.

: int humanYears = scooby.getAgeInHumanYears();

->이를 Dog class에서 method를 정의할 때 int값을 return 하도록 int형으로 정의해준다.

: public int getAgeInHumanYears() { ... return humanAge;}

 

요약을 하자면,
객체들의 공통부분을 모아서 추상화(abstraction)해서 data item과 method로 객체의 틀을 만든 것 == class
class로 new 하여 새로운 객체를 만든 것 == object, instance 
class내에서 행동을 수행하는 statement를 선언하고 객체를 생성했을 때 invoke할 수 있는 것 == method

 


위 내용을 토대로 JAVA의 3가지 변수를 알 수 있다.

1. Class variables : class내에서 static으로 선언한 변수. 즉 class로 접근 할 수 있는 변수를 class variable이라고 한다.

2. Instance variables : class안 method밖에서 선언한 변수. class내 어떤 method에서도 접근할 수 있는 변수를 Instance                                         variable이라고 한다.

3. Local variables : method내에서 선언한 변수. method밖에서 사용할 수 없고 method가 끝나면 소멸하는 변수를

                                  Local variable이라고 한다. (main에서 선언된 variable또한 main에 local이다.)

 

The Keywaord This

'this'는 같은 class내 method에서 instance variable을 사용할때 이 class의 instance variable이라는 것을 명시해주기 위해 사용한다. 원한다면 생략도 가능하다. 

ex) this.name = keyboard.nextLine();  //class내 instance variable인 name임을 명시해줌.

다른 class에서 객체를 생성하고 해당 method를 사용할때 this가 객체의 이름으로 바뀐다.

 

+parameter과 argument의 차이점)

parameter과 argument는 서로 교환하여 사용할 수 있지만 차이점은 있다. parameter는 method를 정의할때 사용하는 변수를 말하고, argument는 실제로 invoke할때 값을 넣는 것을 말한다.