2023.01.10
- static : 정적(전역적) 변수 선언에 사용
- final : 변경할 수 없는, 상속불가
- this() - 자기 클래스의 생성자 호출
- this.메소드명() - 자기 클래스의 메소드를 호출
- this.필드명 - 자기 클래스의 필드(변수)
- super() - 부모 클래스의 생성자 호출
- super.메소드명() - 부모 클래스의 메소드를 호출
- super.필드명 - 부모 클래스의 필드(변수)
over loading : 동명의 메소드를 매개변수 type과 길이에 따라 여러개 만들 수 있음 = 다형성
매개변수 길이/타입을 달리해서, 같은 이름의 메소드를 여러개 정의할 수 있다.
over riding : 자식클래스의 동명 매소드가 부모클래스의 메소드(무시당한다.)보다 우선실행
= 상속에서 나오는 부작용
부모클래스의 메소드를 자식클래스 안에서 재정의 하면 부모클래스의 메소드는 무시된다.
자식클래스에서 부모클래스의 메소드를 새로 정의할 수 있다.
<Study18>
public class Study18 {
public static void main(String[] args) {
// CellPhone anycall = new CellPhone();
DmbCellPhone dcphone = new DmbCellPhone();
dcphone.setModel("Anycall 2004");
dcphone.setColor("silver");
System.out.println("Model : "+dcphone.getModel());
System.out.println("Color : "+dcphone.getColor());
dcphone.powerOn();
dcphone.bell();
dcphone.sendVoice("여보세요");
dcphone.receiveVoice("누구세요");
dcphone.hangUp();
dcphone.powerOff();
CellPhone anycall = new CellPhone("Galaxy10","white");
System.out.println(anycall.getModel());
System.out.println(anycall.getColor());
anycall.powerOn();
anycall.bell();
anycall.powerOff();
}
}
<CellPhone>
public class CellPhone {
private String model;
private String color;
public CellPhone() {}
public CellPhone(String model, String color) {
this.model=model;
this.color=color;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
void powerOn() {
System.out.println("전원을 켭니다.");
}
void powerOff() {
System.out.println("전원을 끕니다.");
}
void bell() {
System.out.println("벨이 울립니다.");
}
void sendVoice(String message) {
System.out.println("자기 : "+message);
}
void receiveVoice(String message) {
System.out.println("상대방 : "+message);
}
void hangUp() {
System.out.println("전화를 끊습니다.");
}
}
<DmbCellPhone>
//DmbCellphone이 CellPhone을 상속받았다.
public class DmbCellPhone extends CellPhone {
public DmbCellPhone() {
//super();
}
public DmbCellPhone(String model, String color) {
super(model, color);//한줄의 코드로 두개의 일을 하는게 가장 좋다.
// this.setModel(model); 이렇게도 가능하지만 위에 한줄이 훨씬 낫다.
// this.setColor(color);
}
@Override //컴파일이 좀 더 빨라진다.
void powerOn() {
System.out.println("DMB폰 전원을 켭니다.");
}
@Override
void powerOff() {
System.out.println("DMB폰 전원을 끕니다.");
}
@Override
void bell() {
System.out.println("DMB폰 벨이 울립니다.");
}
}
<결과물>
Model : Anycall 2004
Color : silver DMB폰 전원을 켭니다. DMB폰 벨이 울립니다. 자기 : 여보세요 상대방 : 누구세요 전화를 끊습니다. DMB폰 전원을 끕니다. Galaxy10 white 전원을 켭니다. 벨이 울립니다. 전원을 끕니다. |
====================================
<기초(primitive/primary/basic) 데이터 타입>
- int, short, byte, char, long, float, double, boolean
<복합(complex) 데이터 타입>
- String, ArrayList, Array, 클래스명(File, Filewriter),Scanner
house h1 = new Home();
House h1 = (Home) new Home(); 주황색부분을 casting연산자 = 강제타입변환
<Study19>
public class Study19 {
public static void main(String[] args) {
Car car = new Car();
for(int i=1;i<=5;i++) {
int punkLoc = car.run();
switch(punkLoc) {
case 0:
System.out.println("Replace FrontLeft with HankookTire");
car.tire[punkLoc] = new HankookTire("fontLeft",15);
break;
case 1:
System.out.println("Replace FrontRight with GeumhoTire");
car.tire[punkLoc] = new GeumhoTire("fontRight",13);
break;
case 2:
System.out.println("Replace RearLeft with HankookTire");
car.tire[punkLoc] = new HankookTire("rearLeft",14);
break;
case 3:
System.out.println("Replace RearRight with GeumhoTire");
car.tire[punkLoc] = new GeumhoTire("rearRight",17);
}
System.out.println("===========================");
}
}
}
<Car>
public class Car {
// Tire frontLeft;
// Tire frontRight;
// Tire rearLeft;
// Tire rearRight;
Tire[] tire;
public Car() {//생성자에서 초기화하기!!!
tire = new Tire[4];
tire[0] = new Tire("frontLeft",6);
tire[1] = new Tire("frontRight",2);
tire[2] = new Tire("rearLeft",3);
tire[3] = new Tire("rearRight",4);
// this.frontLeft = new Tire("앞왼쪽",6);
// this.frontRight = new Tire("앞오른쪽",2);
// this.rearLeft = new Tire("뒤왼쪽",3);
// this.rearRight = new Tire("뒤오른쪽",4);
}
int run() {
System.out.println("Car is drinving.");
for(int i=0;i<tire.length;i++) {
if(!tire[i].roll()){
this.stop();
return i;
}
}
return -1;
}
void stop() {
System.out.println("Car stops.");
}
}
<Tire>
public class Tire {
public int maxRound; //타이어 최대회전횟수
public int curRound; //타이어의 현재까지 누적회전횟수
public String location; //타이어의 위치
public Tire() {}
public Tire(String loc, int max) {
this.location=loc;
this.maxRound=max;
this.curRound=0;
}
public boolean roll() {
++curRound;
if(curRound<maxRound) {//
System.out.println(this.location+" Tire Left : "+(this.maxRound-this.curRound));
return true;
} else { //curRound >= maxRound
System.out.println(this.location+" Tire punk !!!");
return false;
}
}
}
<HankookTire>
public class HankookTire extends Tire {
public HankookTire(String loc, int maxRound) {
super(loc,maxRound);
// this.location=loc;
// this.maxRound=maxRound;
// this.curRound=0;
}
@Override
public boolean roll() {
++curRound;
if(curRound<maxRound) {//
System.out.println(this.location+" Hankook Tire Left : "+(this.maxRound-this.curRound));
return true;
} else { //curRound >= maxRound
System.out.println(this.location+" Hankook Tire punk !!!");
return false;
}
}
}
<GeumhoTire>
public class GeumhoTire extends Tire {
public GeumhoTire(String loc, int maxRound) {
super(loc,maxRound);//한줄로 코딩
// this.location=loc;
// this.maxRound=maxRound;
// this.curRound=0;
}
@Override
public boolean roll() {
++curRound;
if(curRound<maxRound) {//
System.out.println(this.location+" Geumho Tire Left : "+(this.maxRound-this.curRound));
return true;
} else { //curRound >= maxRound
System.out.println(this.location+" Geumho Tire punk !!!");
return false;
}
}
}
<결과물>
Car is drinving.
앞왼쪽 Tire Left : 5 앞오른쪽 Tire Left : 1 뒤왼쪽 Tire Left : 2 뒤오른쪽 Tire Left : 3 =========================== Car is drinving. 앞왼쪽 Tire Left : 4 앞오른쪽 Tire punk !!! Car stops. Replace FrontRight with GeumhoTire =========================== Car is drinving. 앞왼쪽 Tire Left : 3 fontRight Geumho Tire Left : 12 뒤왼쪽 Tire Left : 1 뒤오른쪽 Tire Left : 2 =========================== Car is drinving. 앞왼쪽 Tire Left : 2 fontRight Geumho Tire Left : 11 뒤왼쪽 Tire punk !!! Car stops. Replace RearLeft with HankookTire =========================== Car is drinving. 앞왼쪽 Tire Left : 1 fontRight Geumho Tire Left : 10 rearLeft Hankook Tire Left : 13 뒤오른쪽 Tire Left : 1 =========================== |
=======================================
추상화
<추상클래스 구성>
- 필드(변수)
- 일반메소드 (인터페이스의 default 메소드)
- 추상메소드
- body 부분이 없는걸 추상화라 한다.
abstract class A{
field;(변수)
abstract 추상method();
일반method(){
코딩부분
}
<Study20>
public class Study20 {
public static void main(String[] args) {
//Animal deer = new Animal(); 추상클래스가지고 new를 써서 사용할 수 없다.
Dog chiwawa = new Dog();
chiwawa.sound();
chiwawa.run();
Cat nero = new Cat();
nero.sound();
nero.run();
}
}
<Animal>
public abstract class Animal {//추상메소드는 abstract 써야 한다.
String name;
abstract void sound();//추상메소드는 abstract 써야 한다.
void run() {
System.out.println(this.name+" 달린다.");
}
}
<Dog>
public class Dog extends Animal {
public Dog() {
this.name="강아지";
}
void sound() {
System.out.println(this.name+" 멍멍.");
}
}
<Cat>
public class Cat extends Animal {
public Cat() {
this.name="고양이";
}
void sound() {
System.out.println(this.name+" 애옹.");
}
}
<결과물>
강아지 멍멍.
강아지 달린다. 고양이 애옹. 고양이 달린다. |
========================
인터페이스
<인터페이스 구성>
- 필드(변수)선언 불가
- 상수선언가능 = 인터페이스에 고정된 값, 반드시 초기값을 대입
- 추상메소드
- default 메소드(추상클래스의 일반메소드)
- static 메소드
<Study21>
public class Study21 {
public static void main(String[] args) {
Dog chiwawa = new Dog();
chiwawa.sound();
chiwawa.run();
Cat nero = new Cat();
nero.sound();
nero.run();
}
}
<Behavior>(인터페이스)
인터페이스는 변수를 선언하지 못한다. 그래서 클래스에서 각자 선언해야 한다.
public interface Behavior {//인터페이스 자체가 추상메소드를 뜻하므로 abstract쓰지 않아도 된다.
void sound();
//인터페이스의 default 메소드 = 일반 클래스의 일반메소드
//인터페이스에서 일반메소드를 쓰려면 default를 써야 한다.
default void run() {
System.out.println("달린다.");
};
}
<Dog>
public class Dog implements Behavior {//extends가 아니라 implements를 사용한다
String name;
public Dog() {
this.name="강아지";
}
@Override
public void sound() {
System.out.println(this.name+" 멍멍");
}
}
<Cat>
public class Cat implements Behavior {
String name;
public Cat() {
this.name="고양이";
}
@Override
public void sound() {
System.out.println(this.name+" 애옹");
}
}
<결과물>
강아지 멍멍
달린다. 고양이 애옹 달린다. |
<Study22>
public class Study22 {
public static void main(String[] args) {
//static변수라 클래스와 상관이 없다.그래서 위에다 선언해도 아무 상관없다
RemoteControl.changeBattery();
TV smartTV = new TV();
Audio inkel = new Audio();
smartTV.turnOn();
inkel.turnOn();
smartTV.setMute(false);
inkel.setMute(false);
smartTV.setVolume(7);
inkel.setVolume(6);
smartTV.setMute(true);
inkel.setMute(true);
RemoteControl.changeBattery();
smartTV.turnOff();
inkel.turnOff();
}
}
<RemoteControl>(인터페이스)
public interface RemoteControl {
//상수
public int MAX_VOLUME=10;
public int MIN_VOLUME=0;
//추상메소드
public void turnOn();
public void turnOff();
public void setVolume(int volume);
//디폴드메소드(일반클래스의 일반메소드)
default void setMute(boolean mute) {
if(mute) {
System.out.println("소리를 죽입니다.");
}else {
System.out.println("소리가 납니다.");
}
}
static void changeBattery() {
System.out.println("건전지를 교환합니다.");
}
}
<TV>
public class TV implements RemoteControl {
private int volume;
@Override
public void turnOn() {
System.out.println("TV를 켭니다.");
}
@Override
public void turnOff() {
System.out.println("TV를 끕니다.");
}
@Override
public void setVolume(int volume) {
if(volume>RemoteControl.MAX_VOLUME) {
this.volume=RemoteControl.MAX_VOLUME;
}else if (volume<RemoteControl.MIN_VOLUME) {
this.volume=RemoteControl.MIN_VOLUME;
}else {
this.volume=volume;
}
System.out.println("현재 TV볼륨 : "+this.volume);
}
}
<Audio>
public class Audio implements RemoteControl {
private int volume;
@Override
public void turnOn() {
System.out.println("Audio를 켭니다.");
}
@Override
public void turnOff() {
System.out.println("Audio를 끕니다.");
}
@Override
public void setVolume(int volume) {
if(volume>RemoteControl.MAX_VOLUME) {
this.volume=RemoteControl.MAX_VOLUME;
}else if (volume<RemoteControl.MIN_VOLUME) {
this.volume=RemoteControl.MIN_VOLUME;
}else {
this.volume=volume;
}
System.out.println("현재 Audio 볼륨 : "+this.volume);
}
}
<결과물>
건전지를 교환합니다. TV를 켭니다. Audio를 켭니다. 소리가 납니다. 소리가 납니다. 현재 TV볼륨 : 7 현재 Audio 볼륨 : 6 소리를 죽입니다. 소리를 죽입니다. 건전지를 교환합니다. TV를 끕니다. Audio를 끕니다. |
==================================
<추상메소드vs인터페이스 쓰는법>
