클래스(class) : 현실에서 객체를 만들기 위해서 설계도가 필요하듯 자바에서도 설계도가 필요한데 그것이 클래스이다.
클래스의 구성요소
필드 , 메소드 , 생성자
//public=접근제한자 리턴타입=리턴이 없을시 void speedRun=메소드 이름
//접근제한자 리턴타입 메소드이름(매개변수){
//실행할 코드
//return 리턴값:
//리턴타입일경우 무조건 return이 들어가야 한다
public void speedRun(int s) {
System.out.println(name+"speedRun 메소드 호출됨");
speed = speed + s;
}
public = 접근제한자 void = 리턴타입없음 speedRun = 메소드 이름
실행하게되면 speedRun 메소드 호출됨 프린트 출력후 speed값에 s가 추가된다.
public String getName() {
return name;
}
public String getName(String i) {
return null;
}
public String getName(String i,int j) {
return null;
} // 같은이름으로 메소드는 불가하지만 매개변수가 달라서 에러안뜸.이런게 오버로딩
같은 메소드는 사용불가하지만 매개변수가 달라짐에 따라 사용가능
이같은게 메소드 오버로딩
public Fruit(String name) {
this.name = name;
}
public Fruit(String name, String color) {
this.name = name;
this.color = color;
}
public Fruit(String name, String color, boolean isSeed) {
System.out.println("생성자 1");
this.name = name;
this.color = color;
this.isSeed = isSeed;
}
public Fruit(String name, boolean isSeed, String color) {
System.out.println("생성자 1");
this.name = name;
this.color = color;
this.isSeed = isSeed;
}
매개변수가 다르기 때문에 허용됨.
Board
package day7;
public class Board {
private long no;
private String title;
private int cnt;
private boolean open;
// 생성자
// 1. 기본생성자
// 2. 전체 매개변수
// 메소드
// 1.cnt(조회수 1씩 올리기)
// 2.open(공개비공개) 변경 메소드
// 3.전체 get set 메소드
public Board() {
System.out.println("기본생성자 이용");
}
public Board(long no, String title, int cnt, boolean open) {
System.out.println("전체 매개변수생성자 이용");
this.no = no;
this.title = title;
this.cnt = cnt;
this.open = open;
}
public int cntUp(int a) {
this.cnt= this.cnt+a;
return cnt;
}
public void toggleOpen() {
open = !open;// if문 사용할수있지만 이게깔끔하다.
}
public long getno() {
return no;
}
public void setno(long no) {
this.no = no;
}
public String title() {
return title;
}
public void title(String title) {
this.title = title;
}
public int cnt() {
return cnt;
}
public void cnt(int cnt) {
this.cnt = cnt;
}
public boolean open() {
return open;
}
public void open(boolean open) {
this.open = open;
}
public void cutUp1() {
this.cnt++;
}
}
private = 값을 메인에서 수정할수없도록 막아둠.
return 값이 없고 있고 차이가 크다.
return값이 있다면 system.out.print로 불러올수있지만 ,
return값이 없다면 다른 변수에 저장후에 출력가능하다.( ex) int a = b1.cntUp1(); )
++
public void toggleOpen() {
open = !open;// ( open 값을 변경해준다)
}
는
if(open == true){
open = false;
}else if(open == false){
open = true;
}
와 같다
'Java > Java icia 7일차' 카테고리의 다른 글
필드,메소드,생성자를 이용하여 회원가입 로그인 만들기 (0) | 2023.03.02 |
---|---|
class, method를 이용해 예제 풀기 (0) | 2023.03.02 |