익명 클래스는 일회용으로 인스턴스를 생성하고 버려지는 객체이다. 그러므로 재사용되지 않는다.
//추상클래스 : 추상 메서드를 한 개 이상 포함한 클래스
abstract class Vehicle{
abstract void start(); //추상메서드 : 정의부가 없이 선언부만 존재하는 메서드
void stop() {
System.out.println("Vehicle stop!");
}
}
//class Bus extends Vehicle{
//
// @Override
// void start() {
// System.out.println("Bus start!");
// }
//
//}
public class _01_Anonymous {
public static void main(String[] args) {
//익명 클래스 생성 : Vehicle 상속받는 클래스를 생성
Vehicle v = new Vehicle() {
@Override
void start() {
System.out.println("Bus start!");
}
};
v.start();
v.stop();
}
}
//인터페이스 : 추상메서드로만 이뤄진 클래스
interface Task{
/*public abstract*/ void execute();
}
//class Test implements Task{
//
// @Override
// public void execute() {
// System.out.println("Execute Task");
//
// }
//
// }
public class _02_Anonymous {
public static void main(String[] args) {
Task t = new Task() {
@Override
public void execute() {
System.out.println("Execute Task");
}
};
t.execute();
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class H1 {
public static void main(String[] args) {
JFrame frame = new JFrame("익명 클래스 테스트");
JButton button = new JButton("Click me!");
ActionListener ac = new ActionListener() {
int count = 0;
@Override
public void actionPerformed(ActionEvent e) {
count++;
System.out.println("Click count: " + count );
}
};
button.addActionListener(ac);
frame.setSize(300, 200);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}'JavaStudy' 카테고리의 다른 글
| [Java] synchronized (0) | 2023.12.12 |
|---|---|
| [Java] thread (0) | 2023.12.11 |
| [Java] TreeMap (1) | 2023.12.08 |
| [Java] HashMap과 Hashtable (0) | 2023.12.06 |
| [Java] TreeSet (0) | 2023.12.06 |