관리 메뉴

moozi

상속연습 본문

TIS_2018/응용sw2018_1기

상속연습

moozi 2018. 2. 13. 15:31
상속연습

 

 

class Person{
 private String name;
 Person(String name){
  this.name=name;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public void speak() {
  System.out.println("말하기");
 }
 public void eat() {
  System.out.println("먹기");
 }
 public void walk() {
  System.out.println("걷기");
 }
 public void sleep() {
  System.out.println("잠자기");
 }
}

class Student extends Person{
 Student(String name) {
  super(name);  
 }
 public void study() {
  System.out.println("공부하기");
 }
}

class StudentWorker extends Student{
 StudentWorker(String name) {
  super(name);  
 }

 public void work() {
  System.out.println("일하기");
 }
}

public class ExtendSample {
 static void print(Person p) {
  if(p instanceof Person) {
   System.out.print("Person ");
  }
  if(p instanceof Student) {
   System.out.print("Student ");
  }
  if(p instanceof StudentWorker) {
   System.out.print("StudentWorker ");
  }
  System.out.println();
 }

 public static void main(String[] args) {
  //Person 인스턴스 생성
  Person hkd=new Person("홍길동");
  hkd.sleep();
  hkd.setName("홍길돈");
  System.out.println(hkd.getName());
  
  //Student 인스턴스 생성
  Student lss=new Student("이순신");
  System.out.println(lss.getName());
  lss.study();
  
  //StudentWorker 인스턴스 생성
  StudentWorker sjdw=new StudentWorker("세종대왕");
  System.out.println(sjdw.getName());
  sjdw.work();
  
  print(new Person("왕건"));
  print(new Student("강감찬"));//upcasting.자동변환
  print(new StudentWorker("이황"));//upcasting.자동변환
 }

}

'TIS_2018 > 응용sw2018_1기' 카테고리의 다른 글

자바연습문제07  (0) 2018.02.14
자바연습문제06  (0) 2018.02.13
자바연습문제05  (0) 2018.02.12
자바연습문제04  (0) 2018.02.09
자바연습문제03  (0) 2018.02.08
Comments