[Java]::Remind - Constructor Overloading

Gentlee's Self-Study Log·2023년 4월 20일
0

Java Reminder

목록 보기
3/19
post-thumbnail

Constructor

Constructor = 생성자
클래스(객체) 생성 시 자동으로 생성된다.
클래스의 멤버 변수의 초기화를 하는 역할을 한다.

생성자 오버로딩 예제 코드

package JavaExample;

public class Student {
	
	private String name;
	private int age;
	
	public Student(){
		this("홍길동",25);
	}
	
	public Student(String name) {
		this(name,25);
	}
	
	public Student(int age) {
		this("홍길동",age);
	}
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public void getProfile() {
		System.out.println(this.name+":"+this.age);
	}
	
	public static void main(String args[]) {
		
		Student s1 = new Student();
		Student s2 = new Student(28);
		Student s3 = new Student("최길동");
		Student s4 = new Student("김길동",30);
		
		s1.getProfile();
		s2.getProfile();
		s3.getProfile();
		s4.getProfile();
		
	}
	
}	

결과값-Output

홍길동:25
홍길동:28
최길동:25
김길동:30
profile
https://github.com/SamGentlee

0개의 댓글