▶ 패키지
서로 관련된 클래스들을 묶음
폴더와 비슷한 개념
같은 이름의 클래스를 여러개 만들 때 다른 패키지에 넣으면 구별 가능
다른 패키지에 있는 클래스를 사용하려면 import 해야한다
▶ 접근 제어(access control)
public class A {
private int a; //전용
int b; //디폴트
public int c; //공용
}
public class Test {
public static void main(String args[]) {
A obj = new A();
//obj.a=10; 전용멤버는 다른 클래스에서는 접근 안 됨
obj.b=20; //디폴트 멤버 가능
obj.c=30; //공용 멤버 가능
}
}
public |
공용, 누구나 접근 가능 |
private |
전용, 같은 클래스 안에서만 접근 가능 |
protected |
자식 클래스만 접근 가능 (상속) |
없음 |
디폴트(default), 동일한 패키지 안에서만 접근 가능 |
▶ 정보 은닉(information hiding)
클래스 안의 데이터를 외부에서 마음대로 변경하지 못하게 한다
메소드 | 기능 | |
필드 |
접근자(getters) | 필드값 반환 |
설정자(setters) | 필드값 설정 |
public class Account {
private int regNumber;
private String name;
private int balance;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name; //this : 생성된 객체 자신의 주소를 참조하는
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
public class AccountTest {
public static void main(String args[]) {
Account obj = new Account();
obj.setName("Tom");
obj.setBalance(100000);
System.out.println("이름은 "+obj.getName()+" 통장 잔고는 "+obj.getBalance());
}
}
-접근자와 설정자를 사용하는 이유
- 클래스를 업그레이드할 때 편하다
- 잘못된 값이 넘어오는 경우, 사전 차단할 수 있다
- 필요할 때마다 필드값을 계산하여 반환할 수 있다
- 접근자만을 제공하면 자동적으로 읽기만 가능한 필드를 만들 수 있다
▶ 생성자
클래스 이름과 동일하다
반환값을 가지지 않는다
생성자 이름 앞에 아무 것도 붙이지 않는다
주로 필드에 초기값을 부여할 때 사용된다
생성자는 객체를 만들 때 new 연산자에 의하여 호출된다
※만약 클래스가 생성자를 가지지 않는다면 자바에 의하여 제공되는 기본 생성자를 사용하기 때문에 어떤 클래스든지 생성자가 호출된다.
public class Car {
. . .
Car() { //생성자
. . .
}
. . .
}
-매개변수를 갖지 않는 생성자
public class MyCounter {
int counter;
MyCounter( ) { //생성자
counter =1;
}
}
public class MyCounterTest {
public static void main(String args[]) {
MyCounter obj1 = new MyCounter( ); //MyCounter() : 생성자 호출
MyCounter obj2 = new MyCounter( );
System.out.println("객체 1의 counter = "+obj1.counter); //(실행결과) 객체 1의 counter = 1
System.out.println("객체 2의 counter = "+obj2.counter); //(실행결과) 객체 2의 counter = 1
}
}
-매개변수를 가지는 생성자
public class MyCounter {
int counter;
MyCounter(int value) {
counter =value;
}
}
public class MyCounterTest {
public static void main(String args[]) {
MyCounter obj1 = new MyCounter(100);
MyCounter obj2 = new MyCounter(200);
System.out.println("객체 1의 counter = "+obj1.counter); //(실행결과) 객체 1의 counter = 100
System.out.println("객체 2의 counter = "+obj2.counter); //(실행결과) 객체 2의 counter = 200
}
}
▶ new 연산자
새로 생성된 객체를 가리키는 참조값을 반환한다
이 참조값은 참조변수에 저장된다
▶ 생성자 오버로딩
생성자를 여러개 정의할 수 있다, 매개변수는 다르게 해야한다
public class Student {
private int number;
private String name;
private int age;
private int score;
Student() {
number =100;
name= "New Student";
age = 18;
}
Student(int number, String name, int age) {
this.number=number;
this.name=name;
this.age=age;
}
Student(int score){
this.score=score;
}
void print() {
System.out.println(number+"/"+name+"/"+age+"/"+score);
}
}
설명) 생성자인 Student()의 매개변수를 다르게해서 3개를 만들었다
public class StudentTest {
public static void main(String args[]) {
Student obj1= new Student();
Student obj2= new Student(5,"tom",16);
Student obj3= new Student(60);
obj1.print();
obj2.print();
obj3.print();
}
}
실행결과)
100/New Student/18/0
5/tom/16/0
0/null/0/60
설명) obj1,obj2는 score를 초기화하지 않았기 때문에 자동 초기화값인 0이 출력됐다
obj3는 score를 뺀 나머지가 초기화되지 않아 각 각 0, null, 0으로 출력됐다
▶ 메소드 오버로딩(method overloading)
이름이 같은 메소드를 여러 개 정의하는 것, 매개 변수는 달라야 한다 (매개변수의 개수, 자료형)
public class MyMath {
int square(int i) {
return i*i;
}
int square (int i,int j) {
return i*j;
}
double square (double i) {
return i*i;
}
}
public class MyMathTest {
public static void main(String args[]) {
MyMath obj1 =new MyMath();
System.out.println(obj1.square(5));
System.out.println(obj1.square(5,6));
System.out.println(obj1.square(2.5));
}
}
설명) 변수이름이 같아도 상관 없고, 다만 매개변수의 개수와 자료형만 다르면 메소드 오버로딩 할 수 있다
▶ this
현재 객체를 나타냄
클래스에서 매개변수와 필드의 이름이 같을 때 this로 구별하여 사용
-this()
명시적인 생성자 호출
public class Rectangle {
private int x,y;
private int width,height;
Rectangle(){
this(0,0,1,1);
}
Rectangle(int x){
this(x,x,x);
}
Rectangle(int width, int height) {
this(0,0,width,height);
}
Rectangle(int x, int width, int height){
this(x,0,width,height);
}
Rectangle(int x, int y, int width, int height){
this.x=x;
this.y=y;
this.width=width;
this.height=height;
}
void print() {
System.out.println("좌표: ("+x+","+y+") 가로/세로길이: "+width+"/"+height);
}
}
class RectangleTest {
public static void main(String args[]) {
Rectangle rc1 = new Rectangle();
Rectangle rc2 = new Rectangle(5,6);
Rectangle rc3 = new Rectangle(2,3,4,5);
Rectangle rc4 = new Rectangle(7);
rc1.print();
rc2.print();
rc3.print();
rc4.print();
}
}
실행결과)
좌표: (0,0) 가로/세로길이: 1/1
좌표: (0,0) 가로/세로길이: 5/6
좌표: (2,3) 가로/세로길이: 4/5
좌표: (7,0) 가로/세로길이: 7/7
설명) 객체 rc4의 경우, 매개변수가 하나인 생성자 -> this(x,x,x)이므로 매개변수가 3개인 생성자 -> this(x,0,width,height)이므로 매개변수가 4개인 생성자 실행
'개발 > Java' 카테고리의 다른 글
vscode에서 spring boot 시작하기 (0) | 2023.11.10 |
---|---|
7일차 - 객체지향프로그래밍3 ,상속 (0) | 2019.01.15 |
5일차 - 객체지향 프로그래밍 (0) | 2019.01.08 |
4일차 - 제어문,문자열,배열 (0) | 2019.01.07 |
3일차 - 기초 개념들3 (0) | 2019.01.04 |