본문 바로가기
Development (국비 복습 )/자바

[2023-03-22]인스턴스,VO,오버로딩

by Puddingforever 2023. 3. 22.

car.java  소스를 작성해서 저장

이클립스가 컴파일해서 car.class 바이트코드 파일을 생성

car.class 에 있는 필드값 저장하고 , 메소드 사용하고 싶음

car.class 실행절차

1.객체 생성 : new 생성자코드()

2. 생성된 객체를 변수에 대입

3.사용자 정의 클래스 객체가 대입되는 변수의 타입은 클래스 타입으로 지정

 

Car yourCar = new Car("기아자동차", "소렌토", 2000, "검은색");

 

yourCar는 객체가 대입된 클래스 변수 .

 

 

Student s1 = new Student();  
Student s2 = new Student();	 // stack영역에 각각 기록되고 , heap도 다른 곳에서 씀 
		
//hashCode () heap 영역 메모리 주소를 정수값으로 변환한 것임 
System.out.println("s1.hashCode() : " +s1.hashCode());
System.out.println("s1.hashCode() : " + s2.hashCode());

 

 

값만 가지는 클래스  Domain , VO(value Object) , DTO(Data transfer Object) : 메소드가 정의되지 않고 필드만 있음 !! 

public class Car {
	
	public String company;
	public String model;
	public String color;
	public int maxSpeed;
	public int cc;
	public Korean[] owners;
	
	public Car() {}
	
	//오버로딩
	public Car(String company,String model,String color,int maxSpeed,int cc,Korean[] owners) {
		this.company = company;
		this.model = model;
		this.color = color;
		this.maxSpeed = maxSpeed;
		if(cc <= 999) {
			this.cc = 1000;	
		}else {
			this.cc = cc;
		}
		this.owners = owners;
	}
	
}

 

 

생성자 오버로딩 !! : 동일한 클라스의 생성자를 여러 형태로 만들고 싶을 때 사용한다.  

public Korean() {}	

public Korean(String name,String ssn){
this.name = name;
this.ssn = ssn;
}

public Korean(String name){
this.name=name;

}

생성자를 하나의 클라스에 두개 이상 정의하는 것을 생성자 오버로딩이라고 함 ! 

프로그램 실행시 필요에 따라 , 값을 주고 쓰고 싶을 때도 있고 , 값이 없는 상태에서 쓰고 싶을 때도 있다 

오버로딩 조건)

1.매개변수가 달라야함

2.만약 매개변수의 수가 같다면 타입이 달라야함 

 

 

 

타입을 내가 만든거로 쓰고 싶을 때 

Korean 객체가 담긴 배열 !  

 

 

방법 ! 

 

Korean 클래스를 만들어준다.

public class Korean {

	public String nation = "대한민국";
	public String name;
	public String ssn;

 
	public Korean(String name,String ssn){
		this.name = name;
		this.ssn = ssn;
	}
	
}

Korean 객체의 필드 ! VO다 메소드는 구현 안되어있음 !

 

 

Korean객체가 담긴 배열을 설정하는 방법 ! 

 

방법1) 

Korean[] owners= {new Korean("홍길동",null),
				new Korean("이순신",null),new Korean("슈퍼맨",null)};
                
Car ourCar = new Car("현대자동차", "소나타", "흰색", 145, 2000,owners) ;

 

방법2)

Korean[] owners = new Korean[3];
		Korean owner = null;
		owner = new Korean("홍길동",null);
		owners[0] = owner;
		owner = new Korean("이순신",null);
		owners[1] = owner;
		owner = new Korean("슈퍼맨",null);
		owners[2] = owner;
		
		Car ourCar = new Car("현대자동차", "소나타", "흰색", 145, 2000,owners) ;

 

Korean객체가 담긴 배열을 쓸 때!

 

Korean[] owners = new Korean[3];
		Korean owner = null;
		owner = new Korean("홍길동",null);
		owners[0] = owner;
		owner = new Korean("이순신",null);
		owners[1] = owner;
		owner = new Korean("슈퍼맨",null);
		owners[2] = owner;
		
Car ourCar = new Car("현대자동차", "소나타", "흰색", 145, 2000,owners) ;

String ownerNames = "";
for(Korean myKorean : ourCar.owners) {
    ownerNames  += myKorean.name + " ";

}

 

 

추가 ! , substring()과 lastIndexOf()를 이용하여 마지막 콤마를 빼는 법 

 

  String names = "슈퍼맨,이순신,베트맨,";
     
     String result = names.substring(0,names.lastIndexOf(","));
     
     System.out.println(result);

 


 

마지막 콤마 부분을 삭제하고 싶을 때 ! 

Korean[] owners = new Korean[3];
		Korean owner = null;
		owner = new Korean("홍길동",null);
		owners[0] = owner;
		owner = new Korean("이순신",null);
		owners[1] = owner;
		owner = new Korean("슈퍼맨",null);
		owners[2] = owner;
		
		Car ourCar = new Car("현대자동차", "소나타", "흰색", 145, 2000,owners) ;		
		
		
		System.out.println("제조사: "+ourCar.company);
		String ownerNames = "";
		for(Korean myKorean : ourCar.owners) {
			ownerNames  += myKorean.name + ",";
			
		}
		
		ownerNames = ownerNames.substring(0,ownerNames.lastIndexOf(","));

lastIndexOf(",")  : ,가 들어있는 마지막 인덱스부터 출력된다. 따라서 , 마지막의 ,를 제외하고 출력된다! 

 

 

 

모든 필드를 매개변수에 전달된 값으로 초기화하는 생성자 

All Arguments Constructor  // 웹에서는 @AllArgsConstructor 만들면 파라메터 생성자가 생성됨 

public class Korean {

	public String nation = "대한민국";
	public String name;
	public String ssn;

 
	public Korean(String name,String ssn){
		this.name = name;
		this.ssn = ssn;
	}
	
}

 

메소드 오버로딩 :  동일한 이름을 가진 메소드를 하나의 클라스에서 쓰고 싶을 때 

public int plus(int x,int y) {
		System.out.println("int 타입 매개변수를 사용, plus 메소드");
		return x + y;
	}
	
	//메소드 오버로딩 
public long plus(long x,long y) {
     System.out.println("int 타입 매개변수를 사용, plus 메소드");
     return x + y;
}

1.파라메터 갯수 달라야함

2.갯수가 똑같다면 파라메터의 타입이 달라야함

3.반환타입은 같아도 된다!

 

 

public int plus(int x,int y) {
		System.out.println("int 타입 매개변수를 사용, plus 메소드");
		return x + y;
	}
	
//메소드 오버로딩 
public int plus(long x,long y) {
    System.out.println("int 타입 매개변수를 사용, plus 메소드");
    return 0;
}

위의 코드는 반환타입은 같지만 , 파라메터 타입이 다르기 때문에 에러가 나지 않는다. 파라메터 수가 같다면 , 파라메터 타입은 항상 다르게 해준다. 

 

쓰는 이유: 사용자가 타입만 다르게 하고 동일한 기능을 하는 메소드를 쓰고 싶을 때 , 편리하게 사용할 수 있다. 

 

 

예시)

 

Calculator.class

public class Calculator {
	//필드 
	//생성자
	public Calculator() {
		System.out.println("나는 Calculator 클래스 기본 생성자 입니다.");
		System.out.println("사용중인 heap 메모리 주소를 반환한 정수값:" + this.hashCode());
	}
	
	//메소드 
	public void powerOn() {
		System.out.println("계산기 전원을 켭니다.");
		this.plus(4,3); 
		return ;
	}
	
	public int plus(int x,int y) {
		System.out.println("int 타입 매개변수를 사용, plus 메소드");
		return x + y;
	}
	
	//메소드 오버로딩 
	public long plus(long x,long y) {
		System.out.println("int 타입 매개변수를 사용, plus 메소드");
		return x+y;
	}
	
	public int plus(String x,String y) {
		System.out.println("String 타입 매개변수를 사용하는 plus 메소드");
		return Integer.parseInt(x)+Integer.parseInt(y);
	}
	
	public double divide(int x, int y) {
		return ((double) x) / y; // x가 double타입으로 바뀌니까 , y도 저절로 double타입으로 변환함 
	}
	
	/*
	public double divide(double x , double y) {
		return x/y;
	}
	*/
	
	public void powerOff() {
		System.out.println("계산기 전원을 끄다.");
	}
	
	
}

 

실행메소드가 있는 곳 

public class UseCalculatorClassExample {
	public static void main(String[] args) {
		
		//Calculator.class의 메소드를 사용하고 싶다. 
		Calculator myCalculator = new Calculator();
		myCalculator.powerOn();
	
		
		myCalculator.plus(1L,2L);
		int addResult = myCalculator.plus(3, 4);
		System.out.println("실행결과1: " + addResult);	
		System.out.println("실행결과1: " + myCalculator.plus(3, 4));

	}
}

항상 정수가 등록되면 int로 등록된다. 그래서 기본타입이 int로 되어있는 메소드를 쓴다. 
myCalculator.plus(1, 2);
만약 long타입이 되어있는 메소드를 쓰고 싶으면 , 뒤에 L을 붙여준다.
myCalculator.plus(1L,2L);

 


return;

 

반복문도 나가버리고 메소드 자체를 나가버린다.

public void run() {
		while(true) {
			if(this.gas > 0) {
				System.out.println("달립니다.(gas 잔량: " + this.gas + ")");
				this.gas = this.gas - 1;
			}else {
				System.out.println("멈춥니다." + "(gas 잔량: " + this.gas+")");
				return ; // 메소드를 끝내고 나가버림 
			}
			System.out.println("gas가 남아서 계속 달립니다.");
		}//while-end 
		
	}

 

댓글