728x90
반응형
SMALL
Overloading & Overriding
Overloading
- 오버로딩이란 메서드명은 같고 매개변수 정보는 다른 것이다.
Overloading Condition
- 메서드명이 같아야한다.
- 매개변수 수가 달라야 한다.
- 매개변수 수가 같으면 데이터 타입이 달라야 한다.
public static int add(int n1, int n2) {
return n1 + n2;
}
public static int add(int n1) {
return n1 + 10;
}
반환형은 상관 없다.
Overriding
- 상위 클래스에서 정의한 메서드를 재정의 하는 것이다.
Overriding Condition
- 상위 클래스가 있어야 한다. (상속관계)
- 메서드명이 같아야한다.
- 매개변수 정보가 같아야한다.
- 반환형이 같아야한다.
- 메서드의 내용이 같거나 추가되어야한다.
public class Product {
private String brand;
private String code;
private String name;
private int price;
public Product() {}
public Product(String brand, String code, String name, int price) {
super();
this.brand = brand;
this.code = code;
this.name = name;
this.price = price;
}
public String information() {
String result = String.format("brand : %s, code : %s, name : %s, price : %d ", this.brand, this.code, this.name, this.price);
return result;
}
// Getter & Setter ...
}
public class Desktop extends Product {
protected boolean allInOne;
public Desktop() {}
public Desktop(String brand, String code, String name, int price, boolean allInOne) {
super(brand, code, name, price);
this.allInOne = allInOne;
}
@Override
public String information() {
String superR = super.information() + " || ";
String result = String.format("allInOne : %b", allInOne);
return superR + result;
}
public boolean isAllInOne() {
return allInOne;
}
public void setAllInOne(boolean allInOne) {
this.allInOne = allInOne;
}
}
- 객체는 기본적으로 extends를 작성하지 않아도
Object
최상위 객체를 상속하고 있다. - 대표적으로
toString()
메서드를 재정의 할 수 있다.
public class Person {
private String name;
private int age;
private double height;
private double weight;
public Person() {}
public Person(String name, int age, double height, double weight) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}
@Override
public String toString() {
return String.format("%s, %d, %.1f, %.1f", name, age, height, weight);
}
}
728x90
반응형
LIST
'기술면접' 카테고리의 다른 글
[기술면접준비] 추상 클래스와 인터페이스의 차이 (0) | 2025.05.21 |
---|