티스토리 뷰

반응형

1. 상속(inheritance)

-- Student.java

1
2
3
4
5
6
7
public class Student {
    String name;
    
    public void setName(String name) {
        this.name = name;
    }
}
cs

-- Stu1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package test;
 
public class Stu1 extends Student {  // Student 클래스를 상속    
    public void say() {
        System.out.println("Hi I'm " + this.name);
    }
    
    public static void main(String[] args) {
        Stu1 stu1 = new Stu1();
        stu1.setName("Aaron");  // 상속받은 메서드 "Aaron"
        System.out.println(stu1.name); // "Hi I'm Aaron"
        stu1.say();
    }
}
cs

--

1
2
3
Student stu1 = new Stu1();  // 부모 클래스의 자료형인 것처럼 사용 가능
Object student = new Student();  // 모든 객체는 Object 클래스를 자동으로 상속
Object stu1 = new Stu1();    // 모든 객체는 Object 클래스를 자동으로 상속
cs


2. 오버라이딩(overriding)

-- MasterStu.java

-- 부모 클래스의 메서드를 자식 클래스가 동일한 형태로 덮어쓰기

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MasterStu extends Stu1 {
    public void say() {  // 부모 클래스와 동일한 형태의 메서드
 
        System.out.println("I'm " + this.name + " Nice to meet");
    }
 
    public static void main(String[] args) {
        MasterStu mstu1 = new MasterStu();
        mstu1.setName("Aaron");
        mstu1.say(); // I'm Aaron Nice to meet
    }
 
}

cs



3. 오버로딩(overloading)

-- MasterStu.java

-- 이름은 동일하지만 입력항목이 다른 메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MasterStu extends Stu1 {
    public void say() {  //  
 
        System.out.println("I'm " + this.name + " Nice to meet");
    }
    public void say(String state) { // 동일한 이름의 메서드
        System.out.println(this.name + " is " + state + " Hungry..");
    }
 
    public static void main(String[] args) {
        MasterStu mstu1 = new MasterStu();
        mstu1.setName("Aaron");
        mstu1.say(); // I'm Aaron Nice to meet
        mstu1.say("so"); // Aaron is so Hungry...
    }
}
cs



.

--

--

--

--

반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday