본문 바로가기
Study/Java

[Java] 클래스와 객체의 생성

by JYHAN 2020. 7. 1.

객체 지향 프로그래밍(Object Oriented Programming)

객체란?

프로그래밍에서 속성과 기능을 가지는 프로그램 단위

EX) 계산기 프로그램

속성: +, -, *, /

기능: 연산

 

클래스란?

객체를 만들기 위한 틀이다!!!!

객체를 생성하기 위한 틀로 모든 객체는 클래스(속성[변수] + 기능[메소드])로부터 생성된다

class Dog
// 속성: 크기, 종 등등
// 기능: 짓기, 놀기 등등

// Dog 객체 생성
Dog dog1 = new Dog();
Dog dog2 = new Dog();
Dog dog3 = new Dog();

 

클래스 제작과 객체 생성

public class Dog { // 클래스 이름
	public String color; // 멤버 변수(속성)
	public int age;
	
	public Dog() { // 생성자
		System.out.println("Dog constructor");
	}
	
	public Dog(int a) {
		this.age = a;
	}
	
	public void info() {
		System.out.println(this.age+" "+color);
	}
	public void play() { // 메서드(기능)
		System.out.println("play");
	}
	
	public void bark() { // 메서드(기능)
		System.out.println("Bark!!");
	}
}

public class MainClass {
	public static void main(String[] args) {
		System.out.println("--- Dog1 ---");
		Dog dog1 = new Dog();
		dog1.age = 1;
		dog1.color = "black";
		
		dog1.bark();
		dog1.play();
		dog1.info();
		
		System.out.println("--- Dog2 ---");
		Dog dog2 = new Dog(2);
		dog2.color = "red";
		
		dog2.info();		
	}
}

--- Dog1 ---
Dog constructor
Bark!!
play
1 black
--- Dog2 ---
2 red

 

객체의 생성

ClassName cn = new ClassName() -> 객체를 메모리에 올리는 작업

 

생성자

1. 클래스의 이름과 똑같은 method의 일종
2. 객체 생성시 최초로 호출됨
3. 생성자는 객체의 초기화작업.(전역변수 값설정..)
4. ReturnType이 없다. (void XXXX)

 

사용자 정의 생성자가 없을 경우, default 생성자가 생략되어 있다

사용자 정의 생성자를 하나 이상 만들 경우, default 생성자가 사라진다

 

사용자 정의 생성자 & 디폴트 생성자란?

아래 코드에서 확인!!!

Class Dog{
    String name;
    String color;
    
    // default 생성자
    public Dog(){}
    
    // 사용자 정의 생성자
    public Dog(String n, String c){
    	this.name = n;
        this.color = c;
    }
}

 

댓글