JAVA/코드

자바 -클래스

record2080 2025. 2. 17. 01:32

기본생성자는 생성자를 하나라도 만들면,
그이후로는 기본제공하지 않는다.

class Point {
	int x;
	int y;
	Point(int x,int y) {
		this.x=x;
		this.y=y;
		System.out.println("점 객체가 생성되었습니다.");
	}
}
public static void main(String[] args) {
		
		int a=10;
		int b=20;	
		
		Point point01=new Point(0,0);
		Point point02=new Point(10,20);
				
		System.out.println("점01은 ("+point01.x+","+point01.y+")입니다.");
		System.out.println("점02은 ("+point02.x+","+point02.y+")입니다.");
	}
}

 결과  =>

점 객체가 생성되었습니다.

점 객체가 생성되었습니다.

점01은 (0,0)입니다.

점02은 (10,20)입니다.

 

class Circle {
	String name;
	int radius;
	double area;
	Circle(String name,int radius) {
		this.name=name;
		this.radius=radius;
		this.area=this.radius*this.radius*3.14;
	}
	void printCircleInfo() {
		System.out.println("원 이름 : "+this.name);
		System.out.println("반지름 : "+this.radius);
		System.out.println("넓이 : "+this.area);
	}
}

public class Practice {
	public static void main(String[] args) {
		Circle c1=new Circle("도넛",1);
		Circle c2=new Circle("피자",10);
		
		c1.printCircleInfo();
		c2.printCircleInfo();
	}
}

 

class Book {
	String title;
	String writer;
	Book(String title){
		this.title=title;
		this.writer="작자미상";
	}
	Book(String title,String writer){
		this.title=title;
		this.writer=writer;
	}
	void printBookInfo() {
		System.out.println(this.title+" "+this.writer);
	}
}

public class Practice {
	public static void main(String[] args) {
		
		Book book01=new Book("해리포터","JK롤링");
		Book book02=new Book("춘향전");
		
		book01.printBookInfo();
		book02.printBookInfo();
		
	}
}

 

class Car {
	int currSpeed;
	int maxSpeed;
	Car(int currSpeed){
		this.currSpeed=currSpeed;
		this.maxSpeed=120;

		if(this.currSpeed>this.maxSpeed) {
			this.currSpeed=this.maxSpeed;
			System.out.println("모든 자동차들은 최대 속도가 "+this.maxSpeed+"을 넘길수없습니다.");
		}
	}
}

public class Practice {
	public static void main(String[] args) {
		Car car=new Car(100);
		System.out.println("현재속도 : "+car.currSpeed);
	}
}

'JAVA > 코드' 카테고리의 다른 글

캡슐화와 오버라이딩 활용 예제  (0) 2025.02.23
다형성의 예시  (0) 2025.02.23
15일차 과제 - UPDOWN게임  (0) 2025.02.06
JAVA의 메소드 유형  (0) 2025.02.02
정렬 - 선택, 버블, 삽입  (0) 2025.01.30