1. 같은 패키지 내에 있는 다른 클래스의 메소드 쓰기
package orgOpenTutorials;
public class OkJavaGoInHome {
public static void main(String[] args) {
String id = "JAVA APT 507";
//Elevator call
Elevator myElevator = new Elevator (id);
myElevator.callForUp(1); //올라가기위해 1층으로 엘베를 보내라
// Security off
Security mySecurity = new Security(id);
mySecurity.off();
// Light on
Lighting hallLamp = new Lighting (id+" / Hall lamp");
hallLamp.on();
Lighting floorLamp = new Lighting (id + " / Floor lamp");
floorLamp.on();
}
}
* 클래스 Elevator를 통해서 myElevator라는 이름을 가진 객체를 new 연산자를 통해서 생성을 함.
그렇게 새로 만들어진 myElevator를 통해서 Elevator클래스에 있는 사용가능한 기능과 변수들을 사용가능할 수 있게됨
2. 다른 패키지 내에 있는 클래스의 메소드 쓰기
package org;
import orgOpenTutorials.Elevator;
import orgOpenTutorials.Lighting;
import orgOpenTutorials.Security;
public class OkJavaGoInHome2 {
public static void main(String[] args) {
String id = "Java APT 507";
//Elevator call
Elevator myelevator = new Elevator(id);
myelevator.callForUp(1);
// Security off
Security mySecurity = new Security(id);
mySecurity.off();
// Light on
Lighting HallLamp = new Lighting(id + " / Hall lamp");
HallLamp.on();
Lighting floorLamp = new Lighting(id + " / Floor lamp");
floorLamp.on();
}
}
* import만 추가됐고 나머지는 모두 똑같음. =>
1. 클래스이름을 쓰고 ctrl+space bar 하면 어느위치의 클래스 또는 추천들을 보여주는데, 거기서 선택하면 자동으로 import가 써짐.
2. 직접쓰기 import 패키지명.클래스명;
3. 클래스의 이름앞에 마우스를 가져다대면 1번처럼 진행 가능
사용된 메소드들
package orgOpenTutorials;
public class Elevator {
String _id; //문자열타입 _id 클래스 변수선언
public Elevator(String id) {
this._id = id; // this.을 붙여서 매개변수 id와 클래스변수를 구별
}
//Boolean은 메소드 callForUp의 리턴타입으로 true 또는 false 값을 알려주겠다는 것
public Boolean callForUp(int stopFloor) {
System.out.println(this._id+" → Elevator callForUp stopFloor : "+stopFloor);
return true;
}
public Boolean callForDown(int stopFloor) {
System.out.println(this._id+" → Elevator callForDown : "+stopFloor);
return true;
}
}
package orgOpenTutorials;
//인터페이스는 기능을 명세해서 한 눈에 볼 수 있게하고,
//이름만 나열할 뿐 실제 기능을 구현하지 않는 추상메소드만을 가지고 있는다.
//메소드에 실제로 기능을 넣으려면 구현클래스를 생성하고 객체를 만들어서 진행해야 함
public interface OnOff {
public boolean on();
public boolean off();
}
package orgOpenTutorials;
import java.util.Random;
public class Lighting implements OnOff{ //implements는 인터페이스의 구현을 의미
String _id;
public Lighting(String id){
this._id = id;
}
public boolean on() { //아까 껍데기만 있던 on, off()의 메소드의 기능이 들어가있는 것 확인가능
System.out.println(this._id + " → Lighting on");
return true;
}
public boolean off() {
System.out.println(this._id + " → Lighting off");
return true;
}
public Boolean isOn() {
Random rand = new Random();
return rand.nextBoolean();
}
}
'괴발개발 > Java' 카테고리의 다른 글
Java생활코딩_입력과 출력 (0) | 2021.06.07 |
---|---|
Java생활코딩_디버거 (0) | 2021.06.05 |
Java생활코딩_데이터타입, 변수, 변수선언, 타입변환 (0) | 2021.06.03 |
Java생활코딩_문자열과 문자의 차이 (0) | 2021.06.02 |
Java생활코딩_Hello World 콘솔 출력하기 (0) | 2021.06.02 |