1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | package com.test; import java.util.Random; public class Inheritance { public static void main(String[] args) { //상속, Inheritance // - 클래스간의 상속 // - 뭘 상속?(재산) -> 클래스의 멤버(변수, 메소드) // - 부모 클래스가 가지고 있는 멤버를 자식 클래스에게 물려줘서 자식 코드의 구현을 좀 더 빠르게.,(편하게., 정확하게.,) // - 자식 클래스는 부모가 물려준 멤버를 자신이 직접 선언한것처럼 사용이 가능하다. // - 코드 재사용(************* 생산성↑) //부모 클래스 vs 자식 클래스 //기본 클래스 vs 파생 클래스 //슈퍼 클래스 vs 서브 클래스 Child c = new Child(); c.a = 10; c.b = 10; c.Test(); //부모가 물려준 c.c = 20; c.ccc(); //자기가 가진 //c, d 접근 불가 MyRandom rnd = new MyRandom(); System.out.println(rnd.nextInt()); //1번기능 System.out.println(rnd.getNum()); //2번기능 System.out.println(rnd.getColor()); //3번기능 } } //부모역할 class Parent { //재산 public int a; public int b; public int d; //본인만 쓰기 위한 멤버(자식도 접근을 못함)** public void Test() { } } //자식 역할 class Child extends Parent { public int c; public void ccc() { } } //랜덤 클래스 -> 자식 클래스 구현 //상황] 난수 발생 잦음 //1. Random 클래스 기능 사용 난수 발생(nextInt, nextBoolean.,) //2. 정수(5~10사이) -> Random 클래스 기본 기능 x -> 추가 가공 //3. 색상 난수 -> 새로운 기능 //확장용(파생) class MyRandom extends Random { //1. Random 기본 기능 상속 //2. public int getNum() { Random rnd = new Random(); return rnd.nextInt(6) + 5; //5~10사이 } //3. public String getColor() { Random rnd =new Random(); String[] color = {"red", "orange", "yellow", "green", "blue"}; return color[rnd.nextInt(color.length)]; } } | cs |
'WEB > JAVA' 카테고리의 다른 글
ABSTRACT CLASS(추상클래스)1 (0) | 2015.05.22 |
---|---|
OBJECT CLASS (0) | 2015.05.22 |
CONSTRUCTOR(생성자)3 (0) | 2015.05.22 |
CONSTRUCTOR(생성자)2 (0) | 2015.05.22 |
CONSTRUCTOR(생성자)1 (0) | 2015.05.22 |