추상 클래스, 인터페이스

Jan 01, 2024
추상 클래스, 인터페이스

추상 클래스

💡
  • 이미 존재하는 클래스들의 공통된 부분을 일반화하여 상위 클래스를 만드는 것이다. → 바텀업
  • 공통된 속성이나 메서드를 추상 클래스에 정의하고, 구체적인 구현은 하위 클래스에 맡긴다. 이를 통해 코드의 중복을 줄이고 유지보수를 용이하게 한다.
  • 추상 클래스는 객체가 아니다.
package ex06; abstract class Shape1{ int x,y; public void translate(int x, int y){ this.x = x; this. y = y; } public abstract void draw(); }; class Rectangle extends Shape1{ int width, height; public void draw(){ System.out.println("사각형 그리기 메소드"); } }; class Circle1 extends Shape1{ int width, height; public void draw(){ System.out.println("원 그리기 메소드"); } }; public class Abstract { public static void main(String[] args) { Shape1 s2 = new Circle1(); s2.draw(); } };
 
 

인터페이스

💡
  • 먼저 행동을 정의하고 그 행동을 구현하는 클래스를 만드는 것이다. → 탑다운
  • 인터페이스는 클래스가 어떤 메소드를 반드시 구현해야 하는지를 지정하여 일관성과 안정성을 보장한다. 다중 상속이 가능하므로 여러 인터페이스를 동시에 구현할 수 있고, 특정 동작을 강제화할 수 있다.
package ex07.example; interface Remocon {//객체가 아니다. 그래서 new도 못함 일반 클래스다. void on();// public abstract 생략가능 void off();// public abstract 생략가능 } class SamsungRemocon implements Remocon { @Override public void on() { System.out.println("삼성 리모컨 on"); } @Override public void off() { System.out.println("삼성 리모컨 off"); } } class LgRemocon implements Remocon { @Override public void on() { System.out.println("엘지 리모컨 on"); } @Override public void off() { } } /** * 작성자 : 홍길동 * 날짜 : 2023.12.26 * 구현체 : samsungRemocpn, lgRemocon */ class CommonRemocon{ //p private Remocon r;//인터페이스 or 추상클래스 public CommonRemocon(Remocon r) { this.r = r; } public void on(){ r.on(); } public void off(){ r.off(); } } public class InterEx01 { public static void main(String[] args) { CommonRemocon cr = new CommonRemocon(new SamsungRemocon()); cr.on(); } }
결과
notion image
package ex07.example; // 라이브러리 판매 interface EventListener{ //event를 감지하는 시점이 컴퓨터의 최고 속도로한다. void action(); //시간을 길게잡으면 리소스를 적게 먹는대신 감지가 느리다. //시간을 짧게잡으면 리소스를 많이 먹는대신 감지가 빠르다. } //라이브러리 판매자가 생성 (구현체가 없을경우 내가 생성) class MyApp{ public void click(EventListener l){ l.action(); } } public class InterEx02 { public static void main(String[] args) { MyApp app = new MyApp(); app.click(() -> { System.out.println("회원가입 로직이 실행됩니다."); }); } }
람다 표현식
💡
new를 못하는애들 (추상클래스, 인터페이스)출력할 때
notion image
 
 
 
 
자바는 스윙으로 연습하기 제발 (JFRAME)(389)
package ex07.example; import javax.swing.*; import java.awt.*; class BasicFrame extends JFrame{ public BasicFrame(){ } } public class MyFrameEx01 { static int num =1; public static void main(String[] args) { BasicFrame jf = new BasicFrame(); //jf.setLayout(new BorderLayout()); jf.setSize(300, 500); JButton btn1 =new JButton("더하기"); JButton btn2 =new JButton("빼기"); JLabel la1 = new JLabel(num+""); jf.add("North", btn1); jf.add("South", btn2); jf.add("Center",la1); btn1.addActionListener(e -> { num++; la1.setText(num + ""); }); btn2.addActionListener(e -> { num--; if(num < 0){ num = 0; } la1.setText(num + ""); }); jf.setVisible(true); } }
Share article
RSSPowered by inblog