
: 구현부(몸체)가 없는 메소드를 하나 이상 가지고 있는 abstract 키워드가 있는 클래스를 말한다.
형식:
[접근제어자] abstract class 클래스명{
// 반드시 필수
public abstract 리턴타입 메소드명([매개변수들...]); // 실행문이 따로 없음.}
기능만 변경을 해야할 때, 사용함
class A extends p{
op(){덧셈연산};
}
class B extends p{
op(){곱셈연산};
}
abstract calss p{
abstract op();
}
// 메인 메소드에서 호출할 때? 인가??
P p = new A(); //---> P p= new B(); 곱셈연산으로 바뀜
p.op();
p.op();
p.op();
abstract class Animal { // 추상클래스에서는 abstract 키워드를 꼭 사용
private String astr = "추상클래스";
abstract void cry();// 접근 ---> default
public String getAstr() {
return astr;
}
}
class Cat extends Animal{ // 추상클래스를 상속받으면 반드시 재정의 해줘야 함.
public void cry() { // 추상클래스 실체화함. 재정의는 원래 접근이상으로 선언해줘야함.
System.out.println("냐옹냐옹!");
}
}
class Dog extends Animal{
void cry() {
System.out.println("멍멍!");
}
}
public class AbstractEx {
public static void main(String[] args) {
// 추상 클래스는 인스턴스를 생성할 수 없음.
// Animal a = new Animal();
Cat c = new Cat();
Dog d = new Dog();
c.cry();
d.cry();
System.out.println(d.getAstr());
System.out.println(c.getAstr());
}
abstract class Shape{
public abstract void draw();
}
class Circle extends Shape{
@Override
public void draw() {
System.out.println("원을 그리다."); // 실체화
}
}
public class AbstractEx02 {
public static void main(String[] args) {
Shape ref;
// Shape ref = new Shape(); 로 객체를 생성할 수 없음.
ref = new Circle(); // 상속받은 자식으로만 객체를 생성할 수 있음
// 상속받은 자식 관계가 반드시 성립되어야함.
ref.draw();
}
}
: 특수한 기능을 가진 주석
형식 => @ 명령이름
abstract class Shape1{
public double res = 0;
public abstract double area();
public void printArea() {
System.out.println("면적은 "+ res);
}
}
class Circle1 extends Shape1{
public int r = 5;
@Override
public double area() {
System.out.println("Circle area()메소드");
res = r * r * Math.PI; // java.lang 패키지에 들어있음, static으로 선언되어 있으며, class Math임, 또한 상수임.
// 원의 면적
return res;
}
}
class Rectangle extends Shape1{
public int w = 10, h = 10;
@Override
public double area() {
System.out.println("Rectangle area()메소드");
res = w*h;
return res;
}
}
public class AbstractEx03 {
public static void main(String[] args) {
Shape1 ref = new Circle1();
ref.area();
ref.printArea();
ref = new Rectangle();
ref.area();
ref.printArea();
}
}
: 추상메소드와 상수만 가지고 있는 집합체(묶음)
형식
\[접근제어자] interface 인터페이스명{
\[public static final 숨어있다.] 자료형 필드명;
int a; // 이렇게만 선언불가
int a = 5; // -->public static final int a = 5; 이렇게 선언되어 있는 것임.
\[public abstract 숨어있다.]리턴타입 메소드명(\[매개변수들...]);
ex) public abstract void setA(int a);
void setA(int a);
}
extends : 같은 동급인 경우 사용하는 키워드
ex)
1. 자식클래스 extends 부모클래스
2. 자식클래스 extends 부모추상클래스
3. 자식인터페이스 extends 부모인터페이스
implements : 다른 급인 경우 사용하는 키워드
ex)
1. 자식클래스 implements 부모인터페이스
2. 자식추상클래스 implements 부모인터페이스
**인터페이스는 클래스를 상속받을 수 없다.