- 형변환
* 업캐스팅(upcasting)
① 자식 객체를 부모 타입으로 저장할 수 있다.
② 별도의 코드없이 자동으로 진행된다.
③ 부모 클래스의 메소드만 호출할 수 있다.
④ 자식클래스의 메소드를 호출하려면 강제 casting을 해야한다. -> 다운캐스팅
- 추상클래스
: 추상메서드 + 일반 메서드(iv)
- 추상 메소드
① 본문이 없는 메소드이다.
② 호출을 위해서 존재한다.
- 추상클래스 선언
public abstract class className{
public abstract 타입 메서드이름();
}
- 추상클래스 상속
class child extends abstractName{
public 타입 abstract_메서드이름(){ //꼭 구현
}
}
**** 예제 *****
public class MainClass {
public static void main(String[] args) { //1. stack에 main 호출
Company company = new Company(5); //2.company가 가리키는 Company 객체생성
// 추상 클래스는 객체를 생성할 수 없다.
//company.addStaff(new Staff());
company.addStaff(new SalaryMan(2000000)); //3.Company인스턴스의 addStaff()호출하면서 SalaryMan 객체생성
company.addStaff(new Alba(9200, 200)); //4.Company인스턴스의 addStaff()호출하면서 Alba 객체 생성
company.payInfo(); //5.Company인스턴스 payInfo()호출
}
}
--> 순서에 따른 객체생성
- 인터페이스
- 추상메서드 집합
① 일반 메서드가 없는 추상 클래스를 인터페이스로 작성한다.
② jdk 1.8이후로 default 메소드, static 메소드를 포함할 수 있다.
③ 모든 필드는 final 상수를 가진다. --> 정해진것, 바꾸지 못함
- 인터페이스 생성
interface interfaceName{
//내용이 없는 인터페이스
//자손클래스의 공통된 속성을 묶기 위해 생성가능
}
- 인터페이스 구현
public class child implements interfaceName{
public void~~(){
}
}
**** 예제 *****
public interface Walkable {
// 내용이 없는 인터페이스
// 인터페이스를 타입으로 사용하기 위해서 사용한다.
}
public class Pet {
private String name;
public Pet(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Dog extends Pet implements Walkable{
public Dog(String name) {
super(name);
}
}
public class Cat extends Pet implements Walkable{
public Cat(String name) {
super(name);
}
}
public class Snake extends Pet{ //Dog, Cat과 달리 Walkable 타입이 없는 Snake
public Snake(String name) {
super(name);
}
}
public class Person {
//산책하기
public void walk(Walkable pet) {
System.out.println("Walking with " + ((Pet)pet).getName());
}
}
public class MainClass {
public static void main(String[] args) {
Person person = new Person();
Dog dog = new Dog("백구");
Cat cat = new Cat("냥이");
Snake snake = new Snake("낼름이");
person.walk(dog);
person.walk(cat);
// person.walk(snake);
}
}
--> 그림으로 관계 보기
Snake는 걸을 수 없는 객체이고, Dog와 Cat은 Pet이면서 걸을 수 있기 때문에 Walkable이라는 인터페이스를 생성해서 구현하게 했다.
개념다시보기
추상클래스 : 추상메서드 + 일반 메서드 + 필드 + 생성자..
인터페이스 : 추상메서드 (+ 상수 + default메서드)
-> 추상메서드는 자손클래스에서 구현하도록 설계! -> 둘 다 자손들에게 표준을 제공할 수 있다.
'국비 > JAVA' 카테고리의 다른 글
문자 기반 (보조)Stream (0) | 2021.09.02 |
---|---|
컬렉션 프레임워크 (0) | 2021.09.01 |
LOMBOK (0) | 2021.09.01 |
메서드,반복문, 조건문을 이용한 자판기만들기 (0) | 2021.08.29 |
Array를 이용해 성적 관리 프로그램 만들기 (0) | 2021.08.27 |
댓글