예제 1
class Box1{
private int width;
private int height;
private int depth;
private int vol;
public Box1(int w, int h, int d){
width = w;
height = h;
depth = d;
}
public Box1() { //default 생성자
width = 1;
height = 1;
depth = 1;
}
public int getVol() {
vol = width*height*depth;
return vol;
}
}
public class BoxTestDemo {
public static void main(String[] args) {
int vol;
Box1 mb1 = new Box1(10,20,30);
Box1 mb2 = new Box1();
vol = mb1.getVol();
System.out.println("mb1 객체의 부피 :" + vol);
vol = mb2.getVol();
System.out.println("mb2 객체의 부피 :" + vol);
//실행결과 mb1 객체의 부피 : 6000
//mb2 객체의 부피 : 1
}
}
예제 2
class Circle{
int radius;
//생성자
Circle(int radius){
this.radius = radius;
}
double getArea(){
return 3.14*radius*radius;
}
}
public class CircleArray {
public static void main(String[] args) {
Circle[] A = new Circle[5];
for(int i=0; i<A.length; i++) {
A[i] = new Circle(i);
}
for(int i=0; i<A.length; i++) {
System.out.println(A[i].getArea());
}
}
}
예제 3
public class SubsInfo {
String name, id, passwd, phNum, addr;
SubsInfo(){
name = "기본 생성자";
}
SubsInfo(String name, String id, String passwd){
this.name = name;
this.id = id;
this.passwd = passwd;
}
SubsInfo(String name, String id, String passwd, String phNum, String addr){
this.name = name;
this.id = id;
this.passwd = passwd;
this.phNum = phNum;
this.addr = addr;
}
//위 두 생성자를 합침
// SubsInfo(String name, String id, String passwd, String phNum, String addr){
// this(name, id, pwd);
// this.phNum = phNum;
// this.addr = addr;
// }
//this()는 생성자 코드에서만 사용할 수 있다. 생성자가 아닌 일반 메소드에서 this()를 사용할 수 없다.
//this()는 생성자의 첫번째에 온다
void change_passwd(String passwd) {
this.passwd = passwd;
}
void set_phNum(String phNum) {
this.phNum = phNum;
}
void set_addr(String addr) {
this.addr = addr;
}
void print_Info() {
System.out.println("이름: " + name);
System.out.println("아이디: " + id);
System.out.println("비밀번호: " + passwd);
System.out.println("전화번호: " + phNum);
System.out.println("주소: " + addr);
System.out.println();
}
}
'Java' 카테고리의 다른 글
[Java] Class (0) | 2022.10.22 |
---|---|
[Java] String Buffer, Tokenizer, Scanner (0) | 2022.10.22 |
[Java] Static (0) | 2022.10.22 |
[Java] 상속 (0) | 2022.10.22 |
[Java] 배열 (Array) (0) | 2022.10.22 |