클래스 실습
학생
번호
국어점수
영어점수
수학점수
총 점
평균
package classTest;
class Student{
//번호
int num;
//국어점수
int koscore;
//수학점수
int mathscore;
//총점
int sumscore;
//평균
double average;
//기본생성자
public Student() {
;
}
//초기화 생성자
public Student(int num, int koscore, int mathscore) {
super();
this.num = num;
this.koscore = koscore;
this.mathscore = mathscore;
this.sumscore = koscore + mathscore;
this.average = Double.parseDouble(String.format("%.3f", sumscore/3.0));
}
}
public class ClassTask2 {
public static void main(String[] args) {
Student 강민정 = new Student();
강민정 = new Student(1,23,43);
System.out.println(강민정.average);
System.out.println(강민정.sumscore);
}
}
상점
상품명
상품가격
재고
판매하기
손님
이름
휴대폰번호
통장잔고
할인율
*손님마다 할인률 다름
package classTest;
class Store{
String product;
int priprice;
int stock;
public Store() {
;
}
public Store(String product, int priprice, int stock) {
super();
this.product = product;
this.priprice = priprice;
this.stock = stock;
}
void sell(Customer customer) { //class 를 매개변수로 받을 수도 있다.
customer.bankbook -= priprice - priprice*(customer.discountRait/100);
stock --;
}
}
class Customer{
String customerName;
String fonnum;
int bankbook;
int discountRait;
public Customer() {
;
}
public Customer(String customerName, String fonnum, int bankbook, int discountRait) {
super();
this.customerName = customerName;
this.fonnum = fonnum;
this.bankbook = bankbook;
this.discountRait = discountRait;
}
}
public class ClassTask3 {
public static void main(String[] args) {
Store 민정샵 = new Store("가방",2_0000,4);
Customer 민정 = new Customer("민정","01088454426",30000,24);
민정샵.sell(민정);
System.out.println(민정샵.stock);
System.out.println(민정.bankbook);
}
}
최댓값과 최솟값 구하는 메소드 선언
결과
최대값
최소값
package classTest;
public class Result {
int max;
int min;
public Result() {;}
public Result(int max, int min) {
super();
this.max = max;
this.min = min;
}
}
package classTest;
public class ClassTask4 {
//클래스로 리턴할 때
//각 필드에 직접 접근하여 원하는 위치에 사용할때 (이경우 data[0] 이런식으로 접근하면 max인지 접근해봐야 안다
//배열로 리턴할 때
//모든 데이터를 순서대로 사용할때(이경우 data[0] 이런식으로 접근하면 max인지 접근해봐야 안다)
Result getMaxandMin(int[]arData) { //class를 return 할 수도 있다.
Result result = new Result(arData[0],arData[0]); //위에서 초기화생성자 보고 arData[0]으로 초기화시켜준다.
for(int i=0; i<arData.length; i++) {
if(result.max<arData[i]) {
result.max = arData[i];
}
if(result.min>arData[i]) {
result.min = arData[i];
}
}
return result;
}
public static void main(String[] args) {
ClassTask4 classTask4 = new ClassTask4();
int arData[] = {5,6,8,2,7};
Result result = classTask4.getMaxandMin(arData);
System.out.println(result.min);
System.out.println(result.max);
}
}
Result result = classTask4.getmaxandMin 에서 getMaxandMin 함수가 new 로 Result() 생성자를
사용해주고 있기 때문에 main 함수에서는 생성자를 heap 메모리에 할당하지 않는다.
이렇게 함수 안에서 생성자를 이용해 메모리에 할당할수도 있다.
상속 (inheritance)
1. 기존에 선언된 클래스의 필드를 새로 만든 클래스의 필드로 사용하고자 할 때
2. 여러 클래스 선언 시 필드가 겹칠 때 부모 클래스를 먼저 선언하고
공통 필드를 묶어서 자식 클래스들에게 상속해준다. (추상화)
상속 문법
class A {
A필드
}
class B extends A{
A필드, B필드
}
A : 부모클래스 , 상위클래스, 슈퍼클래스 , 기반클래스
B : 자식클래스, 하위클래스 , 서브클래스, 파생클래스
*자식생성자 호출하면 부모생성자부터 호출되고 자식호출됨
*super(); 은 부모, this(); 는 나
suepr() : 부모생성자
자식 클래스 타입의 객체로 부모필드에 접근할 수 있다.
하지만 자식 생성자만 호출하기 때문에 , 자식필드만 메모리에 할당된다고 생각할 수 있다.
사실 자식 생성자에는 항상 부모 생성자를 호출하기 때문에 자식 생성자 호출 시 부모와 자식 필드 모두
메모리에 할당된다. 이 때 부모 생성자를 호출하는 방법는 super() 를 사용하는 것이다.
만약 , super()를 작성하지 않더라도 컴파일러가 자동으로 작성해준다.
다형성(polymorphism)
1. 오버로딩
이름이 같은 메서드에 매개변수만 다르게 넣어서 정의
2. 오버라이딩(Overriding)
부모 필드에서 선언한 메소드를 자식 필드에서 수정하고자 할 때 재정의를 해야 한다.
이는 자식에서 부모 필드의 메속드와 동일한 이름으로 선언하는 것이다.
부모 필드가 메모리에 먼저 할당되고 a라는 메소드가 먼저 올라간다고 하면,
자식 필드가 메모리에 할당되면서 재정의한 a메소드가 새롭게 만들어지는 것이 아니라
기존에 할당된 a 메소드 저장공간에 새롭게 재정의한 자식 필드의 소스코드 주소가 들어가게 된다.
따라서 자식 객체로 a 메소드에 접근하면 자식 필드에서 재정의한 소스코드의 내용이 읽히게 된다.
package inheritanceTest;
class A {
String name;
int data;
//기본생성자
public A() {
this.name = "A";
this.data = 10;
}
void printName() {
System.out.println(name);
}
}
class B extends A{
void printData() {
System.out.println(data);
}
}
public class InheritanceTest1 {
public static void main(String[] args) {
B b = new B();
b.printName();
}
}
이렇게 b 인스턴스변수만 만들어도 A 필드까지 쓸 수 있다. b 생성자 앞에 A생성자가 생략되어 있는것.
package inheritanceTest;
class Human{
String name;
public Human() {;}
public Human(String name) {
super();
this.name = name;
}
void eat() {
System.out.println("먹기");
}
void sleep() {
System.out.println("잠자기");
}
void walk() {
System.out.println("걷기");
}
}
class Monkey extends Human{
@Override
void walk() {
System.out.println("두 발로 걷기");
}
}
public class InheritanceTest2 {
public static void main(String[] args) {
Monkey kingkong = new Monkey();
kingkong.walk();
}
}
오버라이딩 하면 부모의 walk 함수 영역에 자식의 walk 내용이 덮어진다.
kingkong.walk() = "두 발로 걷기"
이 때 부모의 walk 내용이 변경됐는데 그럼 부모의 walk 를 쓰고싶을때는 어떻게해요 ?
라고 생각할 수 있다.
이 경우 부모를 상속받은 자식 Monkey 의 필드에서만 덮어진거지
실재로 부모 필드인 Human 에서의 값은 바뀌지 않는다.
즉, Human a = new Human(); 으로 선언했을때
a.walk()는 걷기가 나온다.
package inheritanceTest;
class Car{
//브렌드
String brand;
//색상
String color;
//가격
int price;
//기본생성자
public Car() {
// TODO Auto-generated constructor stub
}
//초기화생성자
public Car(String brand, String color, int price) {
super();
this.brand = brand;
this.color = color;
this.price = price;
}
//열쇠시동 on
void engineStart() {
System.out.println("열쇠 시동 켜");
}
//열쇠시동 off
void engineStop() {
System.out.println("열쇠 시동 꺼");
}
}
class Supercar extends Car{ //Car을 상속받음
//모드
String mode;
//기본생성자
public Supercar() {
// TODO Auto-generated constructor stub
}
//초기화 생성자
public Supercar(String brand, String color, int price,String mode) {
super(brand,color,price);//부모의 생성자 호출 super() 생성자는 상속되지 않기 때문에 불러서 초기화 해줘야 함.
this.mode = mode;
}
//열쇠시동 오버라이드 ->시동으로 바꿈
@Override
void engineStart(){
System.out.println("시동 켜");
}
void engineStop() {
System.out.println("시동 꺼");
}
}
public class InheritanceTask {
public static void main(String[] args) {
Car matiz = new Car();
matiz.engineStart();
Supercar audi = new Supercar("audi","black",200000,"run");
audi.engineStart();
}
}
오버라이딩 했음으로 위와같이 audi.engineStart() 에는 시동켜 가 나온다.
+ super,suprer() 차이
super
상속받은 부모를 가르킨다. super.mode 이런식으로 사용
super()
상속받은 부모의 생성자 호출 , 생성자는 상속되지 않음으로 자식에서 부모를 따로 초기화 해주어야, 자바에서
자동으로 생성해주지만 기본생성자가 아닌 매개변수가 있는 생성자일 경우 직접 매개변수를 넣어
super(x) 이런식으로 초기화 해 주어야 한다.
'웹개발 기초 > java기초' 카테고리의 다른 글
자바 접근자,케스팅,추상클래스와 인터페이스 (0) | 2024.02.12 |
---|---|
자바 class 문제 예시 (1) | 2024.01.21 |
자바 메소드 특징 (2) | 2024.01.21 |
자바 2차원 배열과 메소드 (0) | 2024.01.21 |
자바 배열 (0) | 2024.01.19 |