카테고리 없음
12일차 클래스 객체 [생성자] 개댁갸 /예습30%
바론고
2022. 5. 10. 22:24
생성자와 메소드의 차이
리턴값이 없다
클래스명 과 같아야 한다
public class Warrier {
public static void main(String[] args) {
Human warrier = new Human("준성",13,"롤");
warrier.talk();
}
}
class Warrierup extends Warrier{
public static void main(String[] args) {
//상속 하면 메인메소드는?
//talk 덮어쓰기?
}
void talk(){
System.out.println("하이요 업글전사");
}
}
class Human{
public String name;
public int age;
public String hobby;
public Human(String name, int age, String hobby) {
this.name = name;
this.age = age;
this.hobby = hobby;
}
void talk(){
System.out.println("하이요");
}
}
생성자(Constructor)
public class ConstructorExample {
public static void main(String[] args) {
Constructor constructor1 = new Constructor();
Constructor constructor2 = new Constructor("Hello World");
Constructor constructor3 = new Constructor(5,10);
}
}
class Constructor {
Constructor() { // (1) 생성자 오버로딩
System.out.println("1번 생성자");
}
Constructor(String str) { // (2)
System.out.println("2번 생성자");
}
Constructor(int a, int b) { // (3)
System.out.println("3번 생성자");
}
}
오버로딩(load)과 생성자ㅋ
오버라이딩은 상속과 함께 덮어쓰기 같은거임ㅇ
this()
this() 메서드는 자신이 속한 클래스에서 다른 생성자를 호출하는 경우에 사용
예를 들면 만약 클래스명이 Car라는 Car 클래스의 생성자를 호출하는 것은 Car()가 아니라 this()이고, 그 효과는 Car() 생성자를 호출하는 것과 동일합니다.
this() 메서드는 두 가지조건 .
첫 째로, this() 메서드는 반드시 생성자의 내부에서만 사용.
두 번째로, this() 메서드는 반드시 생성자의 첫 줄에 위치.
lass Example {
public Example() {
System.out.println("Example의 기본 생성자 호출!");
};
public Example(int x) {
this();
System.out.println("Example의 두 번째 생성자 호출!");
Example 클래스는 두 개의 생성자를 가지고 있습니다.
하나는 기본 생성자,, 다른 하나는 매개변수를 받고 있는 생성자.
두 번째 생성자 내부의 첫 번째 줄에 this() 메서드가 포함되어 있습니다.
1. sout ()
2. this(); 의사용
3. sout ()
Example의 기본 생성자 호출!
Example의 기본 생성자 호출!
Example의 두 번째 생성자 호출!