캡슐화는 객체지향의 4가지 개념 중 하나이다. 자바의 Encapsulation(캡슐화)는 데이터(변수) ↔ 데이터에 작용하는 코드(메소드)를 하나의 단위로 묶는 메커니즘이다.
캡슐화에서 클래스의 변수는 다른 클래스로부터 숨겨진다. 그래서, 이를 데이터 은닉이라고도 한다.
To achieve encapsulation in Java
1. Declare the variables of a class as private.
2. Provide public setter and getter methods to modify and view the variables values.
Object-oriented Programming (객체지향프로그래밍)
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
get() //Provides read-only, set() //Provides write-only데이터 은닉은 구현 세부 사항을 숨겨 데이터 멤버 엑세스를 제한하는 방법이다.
public class Main2 {
public static void main(String[] args) {
Person person = new Person(25);
person.afterTenyears(25);
}
}
---------------------------
class Person {
static String stt = " // 이건 static!";
private int age;
public int getAge() { //read-only
return age;
}
public void setAge() { //write-only
this.age = age;
}
Person(int age){
System.out.println(age + this.stt);
}
void afterTenyears(int age) {
age += 10;
System.out.println("After 10 years : " + age + this.stt);
}
}
private field age ⇒ Since it is private, it cannot be accessed from outside the class.
외부 클래스로부터 접근이 허용되지 않는다.
In order to access age ⇒ getAge, setAge를 사용한다. (Getter&Setter)
⭐️ age 필드를 private으로 선언함으로써, 권한이 없는 외부 클래스로부터 접근을 제한할 수 있다. 이것이 데이터 은닉이다.
Point : 필드를
private으로 선언, 접근할 때는get,set을 사용해서 접근
인터페이스는 자바의 참조타입이다. 클래스와 비슷하게, 추상 메소드의 모음(?)이다. 클래스가 인터페이스를 implements함으로써, 인터페이스의 추상 메소드를 상속한다.
인터페이스는
implements된다.❓Questions
궁금했던 부분이, 왜 인터페이스를 사용하냐는 거다. 클래스 내에서도 동작들을 구현할 수 있는 것 아닌가?
interface A {
...
}
interface B {
...
}
interface C extends A, B {
...
}
getArea() → 다각형의 면적을 구할 때. 각 다각형마다 면적을 계산하는 방법은 다르다.getArea()의 구현은 서로 독립적인데 → 인터페이스는 구체적인 명세서를 제공한다.interface Line {
…
}
interface Polygon {
…
}
class Rectangle implements Line, Polygon {
…
}
I understand now. In line with the concepts of Java object-oriented programming, I think it's about allowing each function to be independent and connected through inheritance.
이해가 된다. 객체지향 프로그래밍인 자바의 Concepts에 걸맞게, 각 기능들이 독립적이고도 상속을 통해 연결될 수 있도록 하는 것 이라고 생각했다.
public class Main {
public static void main(String[] args) {
Rabbit rabbit = new Rabbit();
rabbit.flee();
Hawk hawk = new Hawk();
hawk.hunt();
Fish fish = new Fish();
fish.flee(); fish.hunt();
}
}
public class Fish implements Predator, Prey {
@Override
public void flee() {
System.out.println("This fish is fleeing from a larger fish.");
}
@Override
public void hunt() {
System.out.println("This fish is hunting smaller fish.");
}
}
public interface Predator {
//Do not need to body
void hunt();
}
public interface Prey {
//Do not need to body
void flee();
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Chevrolet", "Camero",2010);
Car car2 = new Car("Ford", "Mustang", 2022);
System.out.println(car2.getMake());
car2.copy(car1);
System.out.println(car2.getMake());
}
}
public class Car {
// --..code..--
public void copy(Car x) {
this.setMake(x.getMake());
this.setModel(x.getModel());
this.setYear(x.getYear());
}
}