티스토리 뷰

TIL/JAVA

객체지향(OOP)상속

YEIKKI 2023. 1. 6. 14:56

상속(자바는 단일상속만 허용)

-기존 클래스로 새로운 클래스를 작성하는것(코드 재사용)

-두 클래스를 부모와 자식으로 관계를 맺어주는것

-자손은 조상의 모든 멤버(필드, 단 생성자 ,초기화블럭은 제외)+메소드를 상속받는다.

-자손의 변경은 조상에 영향을 미치지 않는다.

class 자식클래스 extends 부모클래스{


/// 실행코드
}

포함관계

-한 클래스의 멤버변수로 다른 클래스를 선언하는 것

-작은 단위의 클래스를 만들고 , 이들을 조합해서 클래스를 만든다.

 

상속관계

~은 ~이다.( is --- a)

원(Circle)은 점(Point)이다.

 

포함관계

~은 ~을 가지고있다.(Has ---a)

원(Circle)은 점(Point)을 가지고 있다.

class Forest {
int x;
int y; 
int z;      // 포함관계 사용전
}

class Forest{
Tree t= new Tree(); 
int z;       //포함 관계 사용후


class Tree {
int x;
int y;

}

 

 

모든 클래스의 조상

Object 클래스

-부모가 없는 클래스를 자동적으로 Object 클래스를 상속

-모든 클래스는 Object클래스에 정의된 11개의 메서드를 상속

-toString(),  equals(Object obj), hashcode(),

 

Overriding(오버라이딩)

-상속을 먼저 받고 , 상속 받은 조상의 메서드를 자신에 맞게 변경

 

규칙

-선언부가 조상클래스의 메서드와 일치

-접근제어자를 조상클래스의 메서드보다 좁은 범위로 변경 NO

-예외는 조상 클래스의 메서드보다 많이 선언할 수 없다.

 

용어가 비슷해서 헷갈릴수있지만 전혀 다른 오버로딩 과 오버라이딩

    오버로딩                                                                                                                           오버라이딩                              

기존에 없는 새로운 메서드를 정의하는것(New)                         상속받은 메서드의 내용을 변경하는것( change,modify)  

 

참조변수 super.

-객체 자신을 가리키는 참조변수. 인스턴스 메서드(생성자)내에만 존재

-조상의 멤버를 자신의 멤버와 구별할때 사용

 

super()

-조상의 생성자를 호출할때 사용

-조상의 멤버는 조상의 생성자를 호출해서 초기화

-생성자의 첫줄에 반드시 생성자를 호출해야한다.

-그렇지 않으면 컴파일러가 생성자의 첫줄에 super();를 삽입

"기본 생성자 작성은 필수"

 

class Forest{
String tree;
String flower;
String grass;

Forest(String t, String f, String g){

this.tree=t;
this.flower=f;
this.grass=g;
   }
   
}


class seoulforest extends Forest {

int people;
int Dog;

seoulforest(int p, int d){
super("연초록","장미","초록");
this.people=p;
this.Dog=d;


     }
     
  void method() {
   System.out.println("super.tree====\n"+super.tree);
    System.out.println("super.grass====\n"+super.grass);
    System.out.println("super.flower====\n"+super.flower);
  

     }
}

public class Test{
public static void main(String[] args) {

 seoulforest s= new seoulforest(2,3);
 
   
    s.method();
    
    System.out.println(s.Dog+s.people+s.flower+s.tree+s.grass);
    System.out.println("===강아지=====\n"+s.Dog);
    System.out.println("======사람======\n"+s.people);
   System.out.println("=======나무=======\n"+s.tree);
    System.out.println("=========꽃=======\n"+s.flower);
    System.out.println("====잔디=======\n"+s.grass);

'TIL > JAVA' 카테고리의 다른 글

객체지향(OOP)제어자  (0) 2023.01.11
객체지향(OOP)다형성  (0) 2023.01.09
객체지향(OOP)메서드  (0) 2022.12.29
객체지향(OOP)Part1요약  (0) 2022.12.26
배열  (0) 2022.12.23