12일차 클래스 예제

박현정·2022년 3월 29일
0

JAVA 독학

목록 보기
17/26

(예제)

//강아지, 고양이, 돼지
//색깔, 이름, 나이
//생성자를 사용해서 초기화 하기
//생성자 단축키 : Alt + Shift + S > O

public class Animal {
int age;
String color;
String name;
String sound;
String feed;

	Animal(){}

public Animal(int age, String feed, String color, String name, String sound) {
	
	this.age = age;
	this.color = color;
	this.name = name;
	this.sound = sound;
	this.feed = feed;
}

void getSound(){
	System.out.println(sound);
}

void eat() {
	System.out.println(name+"이(가)"+feed+"을(를) 먹는중.");
}

void sleep() {
	System.out.println(name+"이(가) 자는 중");
}

void showInfo() {
	System.out.println(age+"세\n"+"색상은 "+color+"\n이름은 "+name);
}
public static void main(String[] args) {
	Animal dog = new Animal(4,"사료","하얀색","다미","멍멍");
	Animal cat = new Animal(10,"참치캔","검은색","누리","야옹");
	Animal pig = new Animal(4,"피자","핑크색","뙈지","꿀꿀");
	
	dog.showInfo();
	dog.eat();
	dog.sleep();
	dog.getSound();
	
	cat.showInfo();
	pig.showInfo();
	
	
	
}
}

(결과창)

profile
Gut Beginer

0개의 댓글