[Java]/Program source (java)
113 - Java 상속(Inheritance) : 부모 클래스 A 클래스의 write 함수를 이용하여 자식 클래스에서 사용하기
Jelly-fish
2023. 9. 13. 15:26
/*===========================
■■■ 클래스 고급 ■■■
- 상속(Inheritance)
=============================*/
// 다음과 같은 프로그램을 구현한다.
// 단, 상속의 개념을 적용하여 작성할 수 있도록 한다.
// 실행 예)
// 임의의 두 정수 입력(공백 구분) : 20 10
// 연산자 입력(+ - * /) : -
// >> 20 - 10 = 10
// 계속하려면 아무 키나 누르세요...
//import java.util.Scanner;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class Aclass
{
protected int x, y;
protected char op;
Aclass()
{
}
void write(double result)
{
System.out.printf("\n>> %d %c %d = %.2f\n", x, op, y, result);
}
}
// [참고 사항!!]***************************************************************
// this : 내가 나를 부를때
// ob : 외부에서 보는 나
// super : 내가 부모에게 접근...
// 자식에 대한 인스턴스 생성 구문에서 자식만 메모리 할당되는 것이 아니다.
// 부모도 같이 메모리에 퍼올려진다...!!!!
// 상속받은 만큼 책임을 진다! ( 재산을 상속받으면, 상속세를 내는 것처럼... )
// 자신의 인스턴스가 생성될 때 부모의 멤버들도 모두 메모리에 퍼올린다!!!
// 그 책임의 일부 : 자식의 생성자에 부모의 생성자 super()를 호출한다!!
//******************************************************************************
// Aclass 를 상속받는 클래스로 설계
class Bclass extends Aclass
{
/*
protected int x, y;
protected char op;
Aclass()
{
}
void write(double result)
{
System.out.printf("\n>> %d %c %d = %.2f\n", x, op, y, result);
}
*/
Bclass()
{
// super();
}
// 입력 제대로면 : true 입력 뭔가 잘못됐으면 : false
// void input()
boolean input() throws IOException
{
//Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("임의의 두 정수 입력(공백 구분) : "); //"20 10"
String temp = br.readLine();
// ※ 문자열.split("구분자");
// 문자열.split("\\s"); //-- 구분자 → 공백
//
// ex) "10 20 30 40 50".split("\\s");
// → 반환 → {"10", "20", "30", "40", "50"};
//
// ex) "010-1234-4567".split("-");
// → 반환 → {"010", "1234", "4567"};
String[] strArr = temp.split("\\s"); //"20 10" → String[] strArr = {"20", "10"};
//if (temp.length() != 2)
if (strArr.length != 2)
return false;
//-- false 를 반환하며 input() 메소드 종료
// 이 조건을 만족하여 if 문을 수행하게 될 경우...
// 아래 수행해야 할 코드가 남아있더라도
// 결과값(→ false)을 반환하며 메소드는 종료된다.
x = Integer.parseInt(strArr[0]);
y = Integer.parseInt(strArr[1]);
// this.x = Integer.parseInt(strArr[0]);
// B 클래스가 갖고 있는 변수 x → 부모로부터 물려받은 x밖에 없음!
// super.x = Integer.parseInt(StrArr[0]);
// 부모로부터 물려받은 변수 x!
System.out.print("연산자 입력(+ - * /) : ");
op = (char)System.in.read();
/*
if (op!='+' && op!='-' && op!='*' && op!='/') // 만약 or 로 구성하면... - 입력했을 때 첫 번째에서 true 되어버림!
{
return false;
}
return true;
*/
// 부정 → 긍정 : AND → OR
if (op=='+' || op=='-' || op=='*' || op=='/')
{
return true;
}
return false;
}//end input()
double calc()
{
double result = 0;
switch (op)
{
case '+': result = x + y; break;
case '-': result = x - y; break;
case '*': result = x * y; break;
//case '/': result = x / y; break;
//case '/': result = x / y;
case '/': result = (double) x / y;
}
return result;
}//end calc()
/*
print()
{ // 물려받은 거 쓰면 되니까 print 메소드 정의 Ⅹ!
}
*/
}
public class Test113
{
public static void main(String[] args) throws IOException
{
Bclass ob = new Bclass(); // 자식인 B 클래스 인스턴스 생성하면
// → 부모인 A 클래스도 메모리에 올라간다. (의무)
//ob.input();
/*
boolean resp = ob.input();
if (resp != true) // 제대로 입력해서 true 라면 제대로 수행. false 이면... 프로그램 종료!
{
System.out.println("Error...");
return; //-- 프로그램 종료.
}
*/
/*
boolean resp = ob.input();
if (!resp)
{
System.out.println("Error...");
return; //-- 프로그램 종료.
}
*/
if (!ob.input())
{
System.out.println("Error...");
return; //-- 프로그램 종료.
}
double result = ob.calc();
ob.write(result);
}
}
// 실행 결과
/*
임의의 두 정수 입력(공백 구분) : 20 15
연산자 입력(+ - * /) : *
>> 20 * 15 = 300.00
계속하려면 아무 키나 누르십시오 . . .
*/
/*
class Bclass extends Aclass
{
//================================================================================================================
// 오류 났던 거...
// : ① IOException을 import만 하고... Bclass input() 메소드와 main() 메소드에
// : throws IOException 을 작성하지 않았음...
// : ② System.in.read()는 입력받은 문자의 유니코드 숫자(정수)를 받아오는데...
// : op로 입력받은 문자 받아올 때... 강제 형변환 (char)System.in.read(); 를 해주지 않았음...
// : ③ switch (op)까지 쓴 것도 좋았는데... char 타입 op 타입의 문자를 통해 result에 값을 저장하는
// : 과정에서... default를 작성하지 않고, result에 초기값을 주지 않아서 오류 발생...
// : ④ 부모로부터 상속받은 메소드 void write(double result)에서... 매개변수를 주지 않음.
// : ⑤ 부모 클래스에서 double 타입으로 결과를 저장할 result 변수는 상속받지 않았기 때문에
// : 새로 선언해야 하는데 그걸 파악하지 못함...
// =================================================================================================================
public void input() throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.print("임의의 두 정수 입력(공백 구분) : ");
x = sc.nextInt();
y = sc.nextInt();
System.out.print("연산자 입력(+ - * /) : ");
op = (char)System.in.read();
System.in.skip(2);
}
public void calc()
{
// double 타입 result를 부모에게 물려받은 메소드 write(double result)에
// 매개변수로 전달하기 위해, 같은 변수명인 result 를 사용.
// 부모 클래스에서 result 변수를 선언하지 않았기 때문에... this로 호출할 변수 없음.
double result;
switch (op)
{
case '+' : result = x + y; break;
case '-' : result = x - y; break;
case '*' : result = x * y; break;
case '/' : result = x / y; break;
default : result = 0; break;
}
// 부모에게 물려받은 write() 메소드를 사용하여 결과를 출력.
write(result);
}
}
// main() 메소드를 포함하고 있는 외부의 다른 클래스
public class Test113
{
public static void main(String[] args) throws IOException
{
Bclass ob = new Bclass(); // 자식 클래스 Bclass의 인스턴스 생성.
ob.input(); // 자식 클래스 input() 함수 호출. 사용자 2개의 정수 입력, 연산자 문자 입력.
ob.calc(); // 자식 클래스 calc() 함수 호출. 입력받은 값으로 연산 수행.
}
}
*/