자바의 상속에 대해 학습하세요.
class SubClass extends SuperClass{}
형식으로 상속extends A, B
불가private
이나 다른 패키지에 있는 default
)Object
super.superVar
super.superMethod()
부모 클래스의 생성자를 호출
자식 클래스가 생성될 때는 부모 클래스의 생성자가 먼저 호출
super()
추가 (부모 클래스의 기본 생성자 호출)오버라이딩
,
로 구분해 던지는 예외 수가 아니라 계층 구조상 하부에 있는 예외 수기 때문에 throws Exception
으로 던진다면 이는 모든 예외의 최고 조상이므로 던질 수 있는 모든 수의 예외를 던진 것@Override
private
final
static
각각이나 이들의 조합으로 오버라이드를 막을 수는 있겠으나 스태틱 메서드 디스패치로 실행은 불가능*매서드와 자율성
객체는 다른 객체와 협력하기 위해 메시지를 전송한다. 수신자는 먼저 수신된 메시지를 이해할 수 있는지 여부를 판단한 후 미리 정해진 자신만의 방법에 따라 메시지를 처리한다. 이처럼 객체가 수신된 메시지를 처리하는 방법을 메서드라고 부른다.
객체지향 프로그래밍 언어에서 메서드는 클래스 안에 포함된 함수 또는 프로시저를 통해 구현된다. 따라서 어떤 객체에게 메시지를 전송하면 결과적으로 메시지에 대응되는 특정 메서드가 실행된다. 메시지를 수신한 객체가 실행 시간에 메서드를 선택할 수 있다는 점은 다른 프로그래밍 언어와 객체지향 프로그래밍 언어를 구분 짓는 핵심적인 특징 중 하나다. 이것은 프로시저 호출에 대한 실행 코드를 컴파일 시간에 결정하는 절차적인 언어와 확연히 구분되는 특징이다.
외부의 요청이 무엇인지를 표현하는 메시지와 요청을 처리하기 위한 구체적인 방법인 메서드를 분리하는 것은 객체의 자율성을 높이는 핵심 메커니즘이다. 이것은 캡슐화라는 개념과도 깊이 관련돼 있다.
출저: 객체지향의 사실과 오해, 조영호
public class DMD {
public static void main(String[] args) {
Shape triangle = new Triangle();
Shape square = new Square();
triangle.printInfo();
square.printInfo();
}
interface Shape {
public void printInfo();
}
static class Triangle implements Shape {
@Override
public void printInfo() {
System.out.println("Triangle");
}
}
static class Square implements Shape {
@Override
public void printInfo() {
System.out.println("Square");
}
}
}
/*
실행결과
Triangle
Square
*/
public class DD {
public static void main(String[] args) {
Painter redPainter = new RedPainter();
List<Shape> shapes = Arrays.asList(new Triangle(), new Square());
for (Shape shape : shapes) {
shape.paintBy(redPainter);
}
}
}
interface Painter {
void paintOn(Triangle triangle);
void paintOn(Square square);
}
class RedPainter implements Painter {
@Override
public void paintOn(Triangle triangle) {
System.out.println("RedPainter paint triangle");
}
@Override
public void paintOn(Square square) {
System.out.println("RedPainter paint square");
}
}
class GreenPainter implements Painter {
@Override
public void paintOn(Triangle triangle) {
System.out.println("GreenPainter paint triangle");
}
@Override
public void paintOn(Square square) {
System.out.println("GreenPainter paint square");
}
}
interface Shape {
public void paintBy(Painter painter);
}
class Triangle implements Shape {
@Override
public void paintBy(Painter painter) {
painter.paintOn(this);
}
}
class Square implements Shape {
@Override
public void paintBy(Painter painter) {
painter.paintOn(this);
}
}
/*
실행결과
RedPainter paint triangle
RedPainter paint square
*/
추상 클래스
abstract class AbstractClass{
...
//추상 메서드
abstract 메서드 선언부();
}
final
대상 | 설명 |
---|---|
클래스 | 상속할 수 없는 클래스 |
메서드 | 재정의할 수 없는 메서드 |
변수 | 초기화하고 나면 값을 변경할 수 없는 상수 |
static
(나중에 나올 곳 애매해서 그냥 여기..)
대상 | 설명 |
---|---|
멤버변수 | 인스턴스 생성하지 않고 공통으로 사용 가능 |
메서드 | 인스턴스 생성하지 않고 호출 가능 |
중첩 클래스 | 정적 중첩 클래스 |
Object
를 상속하며, 상속하는 클래스가 없는 클래스를 작성해도 extends Object
를 컴파일러가 자동으로 추가Object
선언을 사용해 객체 전달 가능Object
의 메서드 참고java.laing
패키지에 존재Modifier and Type | Method and Description |
---|---|
protected Object | clone() Creates and returns a copy of this object. |
boolean | equals(Object obj) Indicates whether some other object is "equal to" this one. |
protected void | finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. |
Class<?> | getClass() Returns the runtime class of this Object . |
int | hashCode() Returns a hash code value for the object. |
void | notify() Wakes up a single thread that is waiting on this object's monitor. |
void | notifyAll() Wakes up all threads that are waiting on this object's monitor. |
String | toString() Returns a string representation of the object. |
void | wait() Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. |
void | wait(long timeout) Causes the current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. |
void | wait(long timeout, int nanos) Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed. |
equals()
public boolean equals(Object obj) {
return (this == obj);
}
hashCode()
equals()
를 재정의 했다면 hashCode()
도 그에 맞게 적절한 재정의 필요HashMap
, HashSet
HashTable
등에서 문제 발생할 수 있기 때문에hashCode()
확인하고 싶다면 System.identityHashCode()
사용toString()
getClass().getName() + '@' + Integer.toHexString(hashCode())
반환clone()
clone()
을 사용하려면 Cloneable
인터페이스 작성과 구현 필수 public interface Cloneable {}