package test;
public class Person {
private String name;
private int age;
public Person() {
this("이름",100);
}
public Person(String name) {
this.name=name;
}
public Person(int age) {
this.age=age;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void prn() {
System.out.println("이름 : "+name);
System.out.println("나이 : "+age);
public void prn(String name) {
this.name=name;
System.out.println("이름 : "+name);
System.out.println("나이 : "+age);
public void prn(int age) {
this.age=age;
System.out.println("이름 : "+name);
System.out.println("나이 : "+age);
}
}
}
}
package test;
public class Test1 {
public static void main(String[] args) {
Person p = new Person();
p.prn();
p.setName("김길동");
p.setAge(35);
System.out.println("이름 : " +p.getName());
System.out.println("나이 : "+p.getAge());
Person p2 = new Person("홍길동", 20);
p2.prn();
}
}
<출력>
이름 : null
나이 : 0
이름 : 김길동
나이 : 35
이름 : 홍길동
나이 : 20
- 생성자 오버로딩 : 생성자 이름 동일(받는 값의 개수, 형이 틀림)
package test;
public class Point {
public void prn(int a, int b) {
System.out.println(a +", "+ b);
}
public void prn(double a, double b) {
System.out.println(a +", "+ b);
}
}
package test;
public class Test2 {
public static void main(String[] args) {
Point p = new Point();
p.prn(5, 7);
p.prn(10.5, 20.7);
}
}
객체간 협력
package test;
public class Student {
String name;
int money;
public Student(String name, int money) {
this.name=name;
this.money=money;
}
public void takeBus(Bus bus) {
bus.take(1000);
this.money=this.money-1000;
}
public void takeSubway(Subway subway) {
subway.take(1500);
this.money=this.money-1500;
}
public void prn() {
System.out.println(this.name+", "+this.money);
}
}
package test;
public class Bus {
int busNum;
int busMoney;
public Bus(int busNum) {
this.busNum=busNum;
}
public void take(int busMoney) {
this.busMoney = this.busMoney + busMoney;
}
public void prn() {
System.out.println(this.busNum+", "+this.busMoney);
}
}
package test;
public class Subway {
String lineNum;
int subMoney;
public Subway(String lineNum) {
this.lineNum = lineNum;
}
public void take(int subMoney) {
this.subMoney = this.subMoney + subMoney;
}
public void prn() {
System.out.println(this.lineNum+", "+this.subMoney);
}
}
package test;
public class Test3 {
public static void main(String[] args) {
Student s1 = new Student("홍길동",5000);
s1.prn();
Bus bus100 = new Bus(100);
bus100.prn();
s1.takeBus(bus100);
s1.prn();
bus100.prn();
Subway subway1 = new Subway("1호선");
subway1.prn();
s1.takeSubway(subway1);
s1.prn();
subway1.prn();
}
}
<출력>
홍길동, 5000
100, 0
홍길동, 4000
100, 1000
1호선, 0
홍길동, 2500
1호선, 1500