package chapter04;
class Calc {
public static int abs(int a) {
//public int abs(int a) {
// 만약에 static없으면 메인 메소드 안의 Calc.abs(-5); 성립 불가능
// abs는 메소드명, static 공유 가능(별도의 공간 생성), int 반환 타입
// 멤버 변수 => 속성필드, 멤버함수 => 메소드
return a > 0 ? a : -a; // 삼항연산자, a가 0보다 크면 a 아니면 -a 즉, 절댓값
}
public static int max(int a, int b) {
return a > b ? a : b; // 삼항연산자, 최댓값
}
public static int min(int a, int b) {
return a > b ? b : a; // 삼항연산자, 최댓값
}
}
// 클래스 파일안에 public 클래스는 하나만 사용가능
public class CalcEx {
public static void main(String[] args) {
//Calc.abs(-5);
System.out.println(Calc.abs(-5));
System.out.println(Calc.max(10,8));
System.out.println(Calc.min(-3,-8));
}
}
package chapter04;
import java.util.Random;
import java.util.Scanner;
public class guessNumber {
public static void main(String[] args) {
int numberToGuess;
int guess;
Scanner scanner = new Scanner(System.in);
Random generator = new Random();
numberToGuess = generator.nextInt(10)+1;
System.out.println("추측한 숫자를 입력하세요.");
guess = scanner.nextInt();
while (guess != numberToGuess) {
System.out.println("추측한 숫자가 틀립니다.");
//guess = scanner.nextInt();
if (guess >numberToGuess) {
System.out.println("추측한 숫자가 너무 큽니다.");
}else {
System.out.println("추측한 숫자가 너무 작습니다.");
}
System.out.println("추측한 숫자를 입력하세요.");
guess = scanner.nextInt();
}
System.out.println("맞추셨습니다.");
scanner.close();
}
}
(ppt 4장 나머지 진도 나감)
슈퍼 클래스 = 부모 클래스 = 상위클래스
서브 클래스 = 자식 클래스 = 하위클래스
- 서브 클래스객체가 생성될 때, 서브 클래스의 생성자와 슈퍼클래스의 생성자가 모두 실행되는가? 아니면 서브 클래스의 생성자만 실행 되는가?
두 개 다 실행된다.
- 서브 클래스의 생성자와 슈퍼 클래스의 생성자 중 누가 먼저 실행되는가?
먼저 실행되는 것은 슈퍼 클래스의 생성자부터 실행된다. 슈퍼클래스의 생성자 호출 후 서브 클래스 생성자를 호출함
슈퍼 클래스에 여러 생성자가 있을 땐, 서브 클래스의 생성자와 함께 실행될 슈퍼 클래스의 생성자는 원칙적으로 서브 클래스의 개발자가 각 생성자에 대해 함께 실행 될 슈퍼 클래스의 생성자를 지정함.
그러나 명시 하지 않을 경우 컴파일러가 자동으로 슈퍼 클래스의 기본 생성자를 호출하도록 자바 컴파일러가 작동한다.
(이때 기본 생성자가 없으면 오류발생함)
또는 서브클래스의 생성자에서 super()를 이용하면 서브클래스에서 명시적으로 슈퍼클래스의 생성자를 생성 될 수 있다.
super() : 슈퍼 클래스 생성자를 호출 하는 코드. 괄호 안에 인자를 넣을 수 있음.
반드시 생성자의 첫 줄에 사용되어야함.
package chapter05;
class Point {
private int x, y;// 속성 필드 , 같은 클래스까지만
public void set(int x, int y) {
this.x = x;
this.y = y;
}
public void showPoint() {
System.out.println("(" + x + "," + y + ")");
}// public: 접근제어자이지만, 어디든 제한 없이 사용 가능
}//default 클래스
class ColorPoint extends Point {
private String color;
public void setColor(String color) {
this.color = color; // 매개변수를 받은 String color을 필드에 넣어줌.
}
public void showColorPoint() {
System.out.print(color); // String color 출력
showPoint();//위의 Point에서 상속 받아서 사용가능
}
}
// 상속 (부모 Point. 자식 ColorPoint)
public class ColorPointEx {
public static void main(String[] args) {
Point p = new Point();// 객체 생성
// p 는 참조변수(객체 이름)
// 컴파일러할때 기본 생성자 자동 생성됨
p.set(1, 2); // private int x, y; 으로 호출
// => this.x=x; this.y=y; 세팅
p.showPoint();
// p안에 (1,2)가 세팅되어 있고, 위의 showPoint 호출해서 출력함.
ColorPoint cp = new ColorPoint();// 객체생성
//객체 생성하면 기본 생성자가 자동 생성됨.
cp.set(3, 4);//상속받아서 set메소드 사용가능(부모메소드 사용가능)
cp.setColor("red");
cp.showColorPoint();//cp.set(3, 4); 가 가 된 것이
//public void showPoint() {
// System.out.println("(" + x + "," + y + ")");
// } 으로 가서 (x,y)가 출력됨
}
}
package chapter05;
class Point2 {
private int x, y;
public Point2() {// 클래스 Point의 기본 생성자
this.x = this.y = 0;
}
public Point2(int x, int y) {
this.x = x;
this.y = y;
}// (우클릭-source- g c u f)으로 확인가능 단축키 알아두기
// 매개변수를 필드로 세팅함.
public void showPoint() {
System.out.println("(" + x + "," + y + ")");
}
}// default 클래스
class ColorPoint2 extends Point2 {
private String color;
public ColorPoint2(int x, int y, String color) {
super(x, y);
// 기본 생성자가 아닌
// public Point2(int x, int y) {
// this.x = x;
// this.y = y;
// } 매개변수가 있는 생성자로 이동하게 됨.
// => SuperEx 클래스 안에 있는 ColorPoint2 cp = new ColorPoint2(5,6,"blue");
// 을 출력하면 blue(5,6)이 나옴.
this.color = color;
}
public void showColorPoint() {
System.out.print(color);
showPoint();
}
}
public class SuperEx {
public static void main(String[] args) {
ColorPoint2 cp = new ColorPoint2(5, 6, "blue"); // 객체 생성, 매개변수 1개 가짐
// 생성자 호출 =>
// public ColorPoint2(String color) {
// this.color = color;
// }으로 들어와 "blue"가 세팅됨
// 또한 public Point2() {// 클래스 Point의 기본 생성자
// this.x = this.y = 0;
// } 을 호출하여 (0,0)이 됨.
cp.showColorPoint();
}
}
//blue(5,6)
금액 입력 후 지폐 및 동전의 갯수 구하기
package chapter05;
import java.util.Scanner;
public class ChangeMoney {
public static void main(String[] args) {
int[] unit = { 50000, 10000, 1000, 500, 100, 50, 10, 1 };// 환산할 돈의 종류
Scanner scanner = new Scanner(System.in);
System.out.print("금액을 입력하시오>>");
int money = scanner.nextInt();
for (int i = 0; i < unit.length; i++) {
int res = money / unit[i];
if (res > 0) {
System.out.println(unit[i] + "원 짜리 : " + res + "개");
money = money % unit[i];
}
}
scanner.close();
}
}
package chapter05;
import java.util.Scanner;
public class Computelnterest {
public static void main(String[] args) {
double balance = 0;
int years =0 ;
Scanner scanner = new Scanner(System.in);
System.out.print("원금을 입력하세요 :");
int principal = scanner.nextInt();
System.out.print("연이율을 입력하세요 :");
double rate = scanner.nextDouble();
balance = principal;
System.out.println("\n연도수 \t원리금");
do {
years++;
balance = (balance*(1.0+rate/100.0));
System.out.println(years+"\t"+balance);
} while (balance <= principal*2.0);
System.out.println("\n필요한 연도수 ="+years);
//언제까지?
scanner.close();
}
}
Upcasting(업캐스팅) 이란?
: 슈퍼클래스의 레퍼런스(참조변수)로, 서브 클래스의 객체를 가리킴.
즉, 서브클래스의 객체에 대한 참조변수를 슈퍼 클래스 타입으로 변환하는 것.
보통은 서브 클래스는 슈퍼클래스의 멤버와 자기 자신의 멤버를 가질 수 있다
그러나 업캐스팅 된 레퍼런스(참조변수)는 슈퍼클래스의 참조변수만 가질 수 있다.
쉽게 말하면 서브클래스 객체이지만 슈퍼클래스의 속성 및 메소드만 사용하겠다
다운캐스팅(downcasting)이란?
:업캐스팅 되었던 객체의 자료형을 다시 하위클래스의 정보를 담는 기능을 하도록 자료형을 서브클래스로 바꾸어서 되돌려 놓는 것
업캐스팅이 되어있어야만 사용 가능하다
print(p);
을 호출 void print(Person person) {
.....
}
:뭐가 올지 모름
객체레퍼런스(참조변수) instanceof 클래스타입
: 객체 타입을 확인 하는 연산자로 , true/false로 결과 반환
: 3은 참조변수가 아님 ==> 오류발생
package chapter05;
class Person{}
class Student extends Person{}
class Researcher extends Person{}
class Professor extends Researcher{}
public class InstanceOfEx {
static void print (Person p) { //Person p=new Student();//객체 생성 , 업캐스팅
if (p instanceof Person) {
System.out.print("Person ");
}
if (p instanceof Student) { //Student 은 Student이므로 출력됨
System.out.print("Student ");
}
if (p instanceof Researcher) { //Student 은 Researcher이 아님.
System.out.print("Researcher ");
}
if (p instanceof Professor) { //Student 은 Professor이 아님.
System.out.print("Professor ");
}
System.out.println();
}
public static void main(String[] args) {
System.out.print("new Student() -->\t"); print(new Student());
//메소드를 호출하는데 Student객체
System.out.print("new Researcher() -->\t"); print(new Researcher());
//메소드를 호출하는데 Researcher 객체
System.out.print("new Professor() -->\t"); print(new Professor());
//메소드를 호출하는데 Professor 객체
}
}
오버라이딩 오버로딩은 추후 다시 정리해서 추가 예정