
객체(object) : 물리적으로 존재하거나 개념적인 것 중에서 다른 것과 식별 가능한 것
//메소드(매개값1, 매개값2,...);
int result = add(10, 20);
객체는 대부분 다른 객체와 관계를 맺고 있다.
집합 관계 : 완성품과 부품의 관계. (자동차는 엔진, 타이어 등으로 구성되니 자동차-부품은 집합관계)
사용 관계 : 다른 객체의 필드를 읽고 메소드를 호출하는 관계. (사람이 자동차에게 달린다와 같은 메소드를 호출하면 사람-자동차는 사용관계)
상속 관계: 부모와 자식 관계.(자동차가 기계의 특징(필드, 메소드)를 물려받으면 기계(부모)-자동차(자식)은 상속관계)
캡슐화(Encapsulation)
상속(Inheritance)
다형성(Polymorphism)
클래스 안에 또 클래스가 있어도 된다
public class Student{
}
public class StudentEx{
public static void main(String[] args){
Student s1 = new Student(); //s1 변수가 Student 객체를 참조
Student s2 - new Student();
}
}
➕ 클래스는 하나의 실행 클래스(main)와 여러 개의 라이브러리 클래스로 이루어져 있다
public class ClassName{
// 필드 : 객체의 데이터가 저장
int fieldName;
// 생성자 : 객체 생성할 때 초기화 역할
ClassName(){
}
// 메소드 : 객체의 동작으로 호출할 때 실행
int methodName(){
}
}
myCar.speed = 60;)public class Car{
String modelName = "현대";
int speed = 300;
boolean end = true;
Body body = new Body(); //참조타입 사용
Car(){
end = false; //객체 내부(생성자)에서 필드값 이용
}
}
public class CarMaker{
public static void main(String[] args){
Car car1 = new Car();
System.out.println("modelName" + myCar.model); //객체 외부에서 필드값 이용
}
}
// 클래스 변수 = new 클래스();
Car car1 = new Car();
new를 이용해 객체 주소를 리턴
new 뒤에 클래스를 적을 수 있는 건, 생성자가 기본으로 만들어지기 때문에 호출 가능한 것이다!
public class People{
String nationality;
String name;
int height;
People(String nationality){ // 1
this(nationality, "홍길동", 175);
}
People(String nationality, String name){ // 2
this(nationality, name, 175);
}
People(String nationality, String name, int height){ // 3
this.nationality = nationality; //this.nationality는 필드값을 가리킴
this.name = name;
this.height = heght;
}
}
public class PeopleEx{
public static void main(String[] args){
People people1 = new People("Korean"); // 1
People people1 = new People("Korean", "김자바"); // 2
People people1 = new People("Korean", "김자바", 180); // 3
}
}
// 리턴타입 메소드명 (매개변수, ...){}
void power(){}
double plus(int x, int y){}
// 가변 길이 매개변수를 갖는 메소드 선언
int sum(int ... values){
}
public class opr{
**int plus(int ... values){**
int sum = 0;
for (int i = 0; i < values.length; i++){
sum += values[i];
}
return sum;
}
}
public class oprEx{
public static void main(String[] args){
opr myOpr = new opr();
**int ans1 = myOpr.plus(1, 2, 3);**
int ans2 = myOpr.plus(new int[] {1, 2, 3});
}
}
이름이 동일한 메소드를 데이터 타입, 개수, 순서가 다르게 표현할 수 있다
public class Cal{
double rect(double width){
return width * width
}
double rect(double width, double height){
return width * height
}
}
public class oprEx{
public static void main(String[] args){
Cal myCal = new Cal();
double ans1 = myCal.rect(10);
double ans2 = myCal.rect(10,20);
}
}
public class cal{
**static** int plus(int x, int y){return x + y};
**static** double pi = 3.14;
}
객체를 생성해서 객체 참조 변수로 접근하는 것보다 클래스 이름으로 접근하는 게 일반적이다.
double ans = 10 * 10 * **cal**.pi;
int ans2 = cal.plus(10, 5);
일반적으로 선언과 동시에 초기화 하지만, 복잡하면 선언만 미리 한 뒤, 정적 블록에서 초기화 해준다.
// 정적 블록 형태
static {
}
static String inf;
static {
inf = a + "-" + b;
}
public class Korean{
final String nation = "대한민국"; // 1
final String ssn;
public Korean(String ssn){
this.ssn = ssn; // 2
}
}
// static final 타입 상수;
static final double EARTH_RADIUS = 6400;
static{
상수 = 초기값;
}
package 상위패키지.하위패키지;
package com.mycompany;
import com.kTire.Tire;
import com.JTire.*; // 다수의 클래스를 사용하는 경우
public class Car{
Tire tire = new Tire();
}
| 접근 제한자 | 사용 범위 | 제한 범위 |
|---|---|---|
| public | 클래스, 필드, 생성자, 메소드 | x |
| protected | 필드, 생성자, 메소드 | 같은 패키지이거나, 자식 객체만 사용가능 |
| (default) | 클래스, 필드, 생성자, 메소드 | 같은 패키지 |
| private | 필드,생성자, 메소드 | 클래스 내부 |
public double speed;
public double getSpeed(){
double km = speed * 1.6;
return km;
}
private double speed;
public void setSpeed(double speed){
if (speed < 0) {
this.speed = 0;
return;
}
else{
this.speed = speed;
}
}
public class Singleton{
// private 정적 필드 선언 & 초기화
private static Singleton singleton = new Singleton();
// 생성자 선언
private Singleton(){
}
//public 정적 메소드 선언
static Singleton getInstance(){
return singleton;
}
}
public class SinEx{
public static void main(String[] args){
// obj1 과 obj2는 같은 객체를 가리키고 있다
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
}
}
이것이 자바다(신용권, 임경균 지음)