티스토리 뷰
반응형
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
} } |
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 |
.
--
--
--
--
반응형
'Web > JAVA' 카테고리의 다른 글
[JAVA] 인터페이스(Interface) (0) | 2019.04.26 |
---|---|
[Java] 생성자(Constructor) (0) | 2019.04.25 |
[Java] 클래스(class), 메소드(Method), Call By Value (0) | 2019.04.21 |
[Java] 제어문 (if, switch/case, while, for, for each) (0) | 2019.04.18 |
[Java] 자료형 (Num,Boolean,Char,String,StringBuffer,Array,List,Map) (0) | 2019.04.18 |
댓글