[Java] Inheritance

immanuelk1m·2023년 6월 9일
0

Java

목록 보기
4/9
post-thumbnail

Inheritance

Classes can be derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class.

클래스는 다른 클래스 등으로부터 파생될 수 있고, 궁극적으로 최상위 클래스에서 파생될 수 있다.

Why??

reuse the fields and methods of the existing class without
having to write them yourself

필드와 메소드들을 상속 받을 class에 따로 작성하지 않아도 된다.

Class Hierarchy

사람도 계보가 존재하듯이 Class도 상속이 여러번 이루어지다보면
계층 구조가 생긴다.

Constructor of Subclass

  • Constructors are not members. so Constructors are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

  • 생성자는 멤버가 아니므로, 생성자는 상속되지 않아 subclass에서 따로 생성자를 호출해주어야 한다.

// Super Class
public class Bicycle 
{
  public int cadence;
  public int gear;
  public int speed;
  
  public Bicycle(int startCadence, int startSpeed, int startGear) 
  {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
  }
}

// Sub Class

public class MountainBike extends Bicycle 
{
	public int seatHeight;
	
    public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) 
    {
    	// super class 생성자 호출
		super(startCadence, startSpeed, startGear);
		seatHeight = startHeight;
	} 
}

Inheritance of Private Member

A subclass inherits all of the public and protected members of its parent

subclass는 protected member만 상속이 가능하다
따라서 Super Class의 멤버를 접근하기 위해서는 getter(), setter()를 사용해야 한다.

Overriding vs Hiding

Overriding

Overriding is the redefinition of methods defined in superclasses in subclasses. Subclasses do not inherit superclass methods as they are, but use new methods with the same signature.

Overriding은 부모 클래스의 메서드를 자식 클래스에서 동일한 메서드 시그니처를 가지고 재정의하는 것을 말한다.

Hiding

Hiding means to redefine the static method defined in the superclass and use it in the subclass.

Reference

부모 클래스의 정적 메서드를 자식 클래스에서 덮어쓰기함으로써 부모 클래스의 정적 메서드가 숨겨진다

Casting Object

an object of one type in place of another type

"상속 관계에 있는 부모와 자식 클래스 간에는 서로 형변환이 가능하다"

작은 집(Super Class)에서 큰 집(Sub Class)으로 이사할 때는 모든 짐을 다 들고 갈 수 있지만(Down Casting), 큰 집에서 작은 집으로 이사할 때는 필요한 짐만 들고가야 한다.

Down casting

부모 Class가 자식 Class Type으로 Casting 되는 것

public class Bicycle
{
	...
}
public class MountainBicycle extend Bicycle 
{
	...
	public static void main(String[] args)
    {
    	Bicycle myBi = new Bicycle();
        MountainBicycle myMountainBi = (MountainBicycle) myBi;
        // Explicit type casing : (type-name) expression
    }
}

Up casting

자식 Class가 부모 Class Type으로 Casting 되는 것

public static void main(String[] args)
{
	MountainBicycle myMountainBi = new MountainBicycle();
    //Bicycle myBi = new Bicycle();
    Bicycle myBi = (Bicycle) myMountainBi;

    System.out.println(myBi instanceof MountainBicycle);
	=> true 
}

만약 Upcasting을 주석처리하고, Bicycle myBi = new Bicycle(); 활성화하게 되면, false가 출력된다.

Multiple Inheritance of State in Class

One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability
to inherit fields from multiple classes

Interface는 기능을 여러 Class에 상속할 수 있지만, Class는 단일 상속만 가능하다. 다중 상속으로 일어나는 여러 이슈를 피하기 위해서인데,
다중상속을 허락하면 다이아몬드 문제, 복잡성 증가, 보안문제가 발생할 수 있다.

쉽게 생각하면 이것 저것 다 섞여 얼굴은 고양이, 코는 코끼리 목은 기린 다리는 닭인 이상한 동물이 만들어지는 것을 피한다고 보면 된다.

Polymorphism

A parent class have various instances (forms) created from its various subclasses

부모 클래스는 다양한 형태로 자식 클래스로 탈바꿈이 가능하고 자식 클래스는 부모 클래스의 필드를 사용할 뿐만 아니라 부모 클래스에서 가지지 못한 unique한 state와 behavior를 가진다.

super / super( )

super

'super' keyword는 superclass의 멤버를 접근하기 위해 사용된다.
subclass의 member 변수와 super class를 구분하기 위해 사용되고,
현재 class는 this.~ 부모 class는 super.~ 로 사용한다.

super( ), super(parameter list)

super( )는 부모 클래스의 생성자로, 자식 클래스 생성 시 부모 클래스의 변수들을 설정해 생성할 수 있다.
생성자는 public 이므로, 자식 클래스에서 사용이 가능하기 때문이다.

생성자 체인

Reference

Variaous method of Object

clone( )

  • class에 Cloneable interface를 implements 해서 사용
  • implements를 하지 않으면 CloneNotSupportedException 발생
Bike mybike2 = mybike1.clone(); 

객체가 외부 객체인 ObjExternal에 대한 참조를 포함하는 경우
ObjExternal의 변경 사항이 그 Clone한 객체에도 바뀐다.
원래 객체와 그 클론이 독립적이지 않기에 이러한 경우에는 Clone을 overriding하여 ObjExternal도 Clone 후 사용해야 한다.

equals( )

  • 두 객체의 값이 동일한지 비교해 True / False Return
  • 주소 값을 비교하는 (==) 연산자와 다름!

finalize( )

  • 객체가 소멸 될때 호출되기로 약속한 메소드 overriding해서 사용

getClass( )

Class 정보 가져온다

  • getClass().getSimpleName() : 클래스의 간략한 이름을 문자열로 반환

  • getClass().getSuperclass() : 객체의 클래스의 상위 클래스에 대한 정보를 반환

  • getClass().getInterfaces() : 객체의 클래스가 구현하고 있는 인터페이스들에 대한 정보를 반환

hashCode( )

메모리에 생성된 객체의 주소를 16진수로 반환

final keyword

final keyword를 사용하면 다른 클래스가 상속할 수 없는 클래스 혹은
Override가 불가능한 메소드로 지정할 수 있다.

abstract keyword

Abstract classes cannot be instantiated, but they can be subclassed.
Abstract method is a method that is declared without an implementation.

abstract 클래스는 인스턴스화 할 수 없으며, 상속을 해서 사용해야 한다.
abstract 메소드는, implementation을 하지 않아도 된다.

public abstract class GraphicObject 
{
  // declare fields
  // declare nonabstract methods
  abstract void draw(); 
  // interface 작성같이 
  // (without braces, and followed by a semicolon  
}

Abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract

추상 클래스를 상속 받은 클래스는 모든 추상 메서드를 구현 해야하고 그렇지 않으면 해당 클래스에도 추상 메서드를 구현해주어야 한다.

Abstract keyword vs Interface

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

공통점으로 둘 다 인스턴스화가 불가능하다는 점이고, implementation을 하지 않은 method 선언이 가능하다는 점이다.

with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.

Abstract Class는 static, final를 제외한 field를 구현 할 수 있고, public, protected, and private 메서드가 구현 가능하다.

With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public.

Interface는 모든 필드가 public, static, final이어야 하고, 모든 메서드가 public으로 선언 되어야한다. 또한 default method는 implementation이 필요하다.

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

Abstract Class는 'Class'이므로 extends로 상속해야하고, 다중 상속이 불가능하고, Interface는 implements로 상속해야하고, 다중상속이 가능하다.

아래 내용의 표를 정리하면 이해하기 수월하다.
Reference

Which should we use, abstract classes or interfaces?

Abstract classes

  • to share code among several closely related classes.
    여러 관련된 클래스 간에 코드를 공유하고 싶을 때

  • expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public
    추상 클래스를 확장하는 클래스들이 많은 공통 메서드나 필드를 가지거나, public 이외의 접근 제어자(protected나 private와 같은)를 필요로 할 때

  • declare non-static or non-final fields
    static이거나 final이 아닌 필드를 선언하고 싶을 때

Interface

  • unrelated classes would implement your interface
    clone(), equals()처럼 서로 관련성 없는 class에 기능을 추가하고 싶을 때

  • to specify the behavior of a particular data type, but not concerned about who implements its behavior
    특정 데이터 타입의 동작을 명시적으로 지정하고, 그 동작을 구현하는 클래스에 대해서는 신경쓰지 않을 때

  • to take advantage of multiple inheritance of type
    타입의 다중 상속을 활용하고 싶을 때

profile
개발 새발

0개의 댓글