결국 무엇이든 해내는 사람

(Java)Day09 - 상속을 확실히 이해해보기2(오버라이딩, super) 본문

두서없는 공부 노트/JAVA

(Java)Day09 - 상속을 확실히 이해해보기2(오버라이딩, super)

kkm8257 2020. 8. 18. 18:01
반응형

 

package Inheritance_ReView;


public class Animal {
	int age;
	String name;
	
	 public Animal(String name,int age) {		
		
		this.name = name;
		this.age = age;
	}



	void walk() {
		 System.out.println(this.name+"이 걷습니다");
	 }
	
	void bark() {
		System.out.println(this.name+"이 짖습니다.");
	}
	
	void run(){
		System.out.println(this.name+"이 달립니다.");
	}
	
	void eat() {
		System.out.println(this.name+"이 밥을 먹습니다.");
	}

	
}

 

상속해줄 클래스(부모)

 

package Inheritance_ReView;

public class Cat extends Animal {

	int sizeOfNail;

	public Cat(String name, int age, int sizeOfNail) {
	
		super(name,age); // super()는 부모의 생성자를 호출함. 고로 super(age,name)은 Animal(age,name)이라는 생성자를 호출함
		this.sizeOfNail=sizeOfNail;  // sizeOfNail은 Cat에있는 멤버변수이므로 this가 올바르다
		
	}

	@Override
	void walk() {
		System.out.println(this.name + "은 사뿐사뿐 걷습니다. ( 오버라이딩 )");
	}

	@Override
	void eat() {
		System.out.println(this.name + "은 조용하게 밥을 먹습니다. ( 오버라이딩 )");
	}
	
	


	

}

 

 

 

package Inheritance_ReView;


public class Dog extends Animal {
	
	String color;
	
	public Dog(String name, int age, String color) {
		super(name,age);
		this.color = color;
	}
	


}

 

dog 와 cat은 상속받은 클래스

cat은 상속받은 메소드와 이름을 동일하게 작성하여 오버라이딩 하였다.

 

package Inheritance_ReView;

public class Main {

	
	public static void main(String[] args) {
		
		Cat cat = new Cat("멍멍이",3,1);
		Dog dog = new Dog("냥냥이",4,"흰색");
		
		
		dog.walk();
		dog.bark();
		dog.run();
		dog.eat();
		
		cat.walk();//오버라이딩
		cat.bark();
		cat.run();
		cat.eat();//오버라이딩
	}
}

 

 

 

출력해보면 바로 이해 쌉가능

반응형
Comments