객체 지향 프로그래밍

 

프로그램을 조립하여 만드는 방식

프로그램을 부분별로 만든 뒤 전체를 구성하는 형식

 

 

 

 

클래스를 토대로 객체를 만드는 과정을 인스턴화(실체)라고 함

이러한 이유로 객체를 인스턴스라고 부르기도 함

 

public class Cat {
//	Cat이란 설계도 안에 속성(attribute)을 정의

//  인스턴스 변수
	String name;
	String breeds;
	double weight;
	
// 메서드
	public void wag() {
		System.out.println("왈왈");
	}

	public void bark() {
		System.out.println("야옹");
	}
//	메서드 오버로딩 : 이름이 같은 메서드를 입력변수를 다르게해서 구분
	public void bark(int times) {
		System.out.println(times + "번 짖기");
	}
}

 

 

객체 생성하기

- new 키워드와 함께 클래스명과 소괄호를 적어 생성

 

public class ObjectTest01 {
	public static void main(String[] args) {
		 Cat c = new Cat();
		 System.out.println("Cat 클래스를 메모리에 저장" + c);
		 System.out.println(c.name);
		 System.out.println(c.breeds);
		 System.out.println(c.weight);
		 
		 c.name = "크림";
		 c.breeds = "비숑";
		 c.weight = 4;
		 
		 System.out.println(c.name);
		 System.out.println(c.breeds);
		 System.out.println(c.weight);
		 
		 
		 }
}

 

 

생성자

클래스로부터 객체를 만드는 특별한 메서드

보통 해당 클래스의 인스턴스 변수의 초기화를 하기위해 사용(생성자 오버로딩을 통해서 초기화)

반환값이 객체의 주소를 반환하므로 타입 자체를 적지 않는다.

자동으로 주소를 반환해서 return을 적지 않는다.

생성자는 저장하면서 자동적으로 생성을 해준다.(.class파일에 저장)

 

public Cat() {
		// TODO Auto-generated constructor stub
}
	
// 생성자 오버로딩
public Cat(String name, String breeds, double weight) {
    super();
    this.name = name;
    this.breeds = breeds;
    this.weight = weight;
}

 

'JAVA > JAVA' 카테고리의 다른 글

[JAVA] 상속  (1) 2023.12.21
[JAVA] 접근 제한자  (0) 2023.12.20
[JAVA] static  (0) 2023.12.20
[JAVA] 배열  (0) 2023.12.19
[JAVA] 메소드  (0) 2023.12.19

+ Recent posts