JAVA/자바(JAVA)문법
[JAVA]Constructor (생성자)자바 함수/ this 설명 간단히
해병1188기
2021. 4. 5. 10:16
728x90
반응형
2021.03.29 - [JAVA/JAVA(자바)설치 및 툴 이용(ECLIPSE)] - [JAVA] 자바 설치 및 환경 하기 JDK 1.8 버전
[JAVA] 자바 설치 및 환경 하기 JDK 1.8 버전
www.oracle.com/kr/java/technologies/javase/javase-jdk8-downloads.html 위 링크 클릭 하면 여기로 온다 각자의 환경에 맞게 설치 하자 나는 윈도우 64 비트 그전 오라클 로그인 필수 1. 다운로든 된거를 실행..
marine1188.tistory.com
개발 환경
Window 10
JDK 1.8
이클립스 2020_03 버전
Constructor (생성자) 함수
- 클래스명과 동일하다.
- 리턴타입 없음( void 조차 사용하지 않음 )
- 중복정의 가능함 ( overload 가능 - 중복함수 )
- default constructor 갖고 있음 (단, 사용자가 생성자 함수를 재정의 하면 디폴트 생성자 함수 기능 상실함 )
- 멤버변수의 초기화 담당 // 중요//
\> this :
꼭 필요한 경우
값을 꼭 들어 들어야와야 할때
- this 는 자기 자신의 시작 주소
- this 는 항상 첫줄에 있어야한다
package ex01.constructor;
public class Point {
private int x,y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void disp() {
System.out.println(x+","+y);
}
}
package ex01.constructor;
public class MainEntry {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point pt = new Point();
pt.disp();
}
}
- default constructor 갖고 있음 (단, 사용자가 생성자 함수를 재정의 하면 디폴트 생성자 함수 기능 상실함 )
에제
package ex01.constructor;
public class Point {
//매개 변수
private int x,y;
// 기능 상실하게 하느게 하는 코드
public Point(int x,int y) {// this 매개 변수를 나타님
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void disp() {
System.out.println(x+","+y);
}
}
maine class 에러 뜬다
package ex01.constructor;
public class MainEntry {
public static void main(String[] args) {
// TODO Auto-generated method stub
// new 에서 에러 뜬다
Point pt = new Point();
pt.disp();
}
}
애러 안뜨게 할려면
package ex01.constructor;
public class MainEntry {
public static void main(String[] args) {
// TODO Auto-generated method stub
Point pt = new Point(1,2);
pt.disp();
}
}
//생성자 총정리 예제
package ex01.constructor;
public class Point {
//매개 변수
private int x,y;
// 기능 상실하게 하느게 하는 코드
public Point(int x,int y) {// this 매개 변수를 나타냄
this.x = x;
this.y = y;
}
public Point(int x) {//매개변수 1개인자 갖는 생성자
this.x =x;
y =5;
}
public Point() {// 디폴트 생성자
x = y = 99;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void disp() {
System.out.println(x+","+y);
}
}
main class
package ex01.constructor;
public class MainEntry {
public static void main(String[] args) {
this 매개 변수를 나타냄
Point pt = new Point(1,2);
pt.disp();
// 디폴트 생성자
Point pt2 = new Point();
pt2.disp();
/매개변수 1개인자 갖는 생성자
Point pt3 = new Point(8);
pt3.disp();
}
}
728x90
반응형