[Java/자바] Encapsulation, Interfaces, Copy objects

sbj·2023년 11월 29일

Java

목록 보기
10/15
post-thumbnail

Encapsulation (캡슐화)

캡슐화는 객체지향의 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


Why Encapsulation? (왜 캡슐화인가?)

  • In Java encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy to read. → 연관된 필드와 메소드를 함께 묶음으로써 ⇒ 코드를 깔끔하고 가독성있게 만들 수 있다.
  • get() //Provides read-only, set() //Provides write-only
    • It helps to decouple components of a system.
      시스템의 구성요소를 분리할 수 있게 해준다.

Data Hiding (데이터은닉)

데이터 은닉은 구현 세부 사항을 숨겨 데이터 멤버 엑세스를 제한하는 방법이다.

Data hiding using the private specifier (private 지정자를 사용한 데이터 은닉)

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);
	}
}
  1. private field age ⇒ Since it is private, it cannot be accessed from outside the class.
    외부 클래스로부터 접근이 허용되지 않는다.

  2. In order to access age ⇒ getAge, setAge를 사용한다. (Getter&Setter)

  3. ⭐️ age 필드를 private으로 선언함으로써, 권한이 없는 외부 클래스로부터 접근을 제한할 수 있다. 이것이 데이터 은닉이다.

    Point : 필드를 private으로 선언, 접근할 때는 get , set을 사용해서 접근


Interfaces (인터페이스)

인터페이스는 자바의 참조타입이다. 클래스와 비슷하게, 추상 메소드의 모음(?)이다. 클래스가 인터페이스를 implements함으로써, 인터페이스의 추상 메소드를 상속한다.

인터페이스는

  • Constants
  • Default methods
  • Static methods
  • nested types을 가질 수 있다.

Class vs Interfaces

  • 인터페이스를 인스턴스화 할 수 없다.
  • 인터페이스는 생성자를 포함할 수 없다.
  • 모든 메소드는 Abstract(추상) 메소드이다.
  • 인터페이스에는 인스턴스 필드가 생성될 수 없다. ⇒ 인스턴스 필드는 static, final로 선언되어야 한다.
  • 인터페이스는 클래스에의해 확장되지 않는다. 클래스에 의해 implements된다.
  • 인터페이스는 여러 인터페이스를 확장할 수 있다.

Why we use Interfaces? (왜 인터페이스를 사용하는가?)

❓Questions
궁금했던 부분이, 왜 인터페이스를 사용하냐는 거다. 클래스 내에서도 동작들을 구현할 수 있는 것 아닌가?

  1. Interfaces help us to achieve abstraction in Java.
    자바의 추상화를 달성할 수 있다.
interface A {
   ...
}
interface B {
   ... 
}

interface C extends A, B {
   ...
}
  1. getArea() → 다각형의 면적을 구할 때. 각 다각형마다 면적을 계산하는 방법은 다르다.
  2. 따라서, getArea()의 구현은 서로 독립적인데 → 인터페이스는 구체적인 명세서를 제공한다.
interface Line {}

interface Polygon {}

class Rectangle implements Line, Polygon {}
  1. Rectangle ⇒ 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에 걸맞게, 각 기능들이 독립적이고도 상속을 통해 연결될 수 있도록 하는 것 이라고 생각했다.


Example

Main

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();
	}
}

Fish

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.");
	}
}

Interfaces

public interface Predator {
	//Do not need to body
	void hunt();
}

public interface Prey {
	//Do not need to body
	void flee(); 
}

Copy Objects (객체 복사)

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());
	}
}

SUMMARY

  • Encapsulation(캡슐화)
    • 객체지향프로그래밍(OOP)의 특징 중 하나.
    • Refers to the bundling of fields and methods inside a single class.
      단일 클래스 내에서 필드와 메소드를 묶는 것을 말한다.
    • It prevents outer classes from accessing and changing fields and methods of a class.
      외부 클래스로부터 클래스의 필드, 메소드가 변경되거나 접근되는 것을 방지한다.

  • Interfaces (인터페이스)
    • 추상 클래스. 추상 메소드의 그룹을 포함한다. (methods without a body)
    • Purpose of Interfaces(인터페이스의 목적)
      • 자바의 추상화 달성 → 각 기능들이 독립적으로 수행될 수 있도록 한다.
profile
Strong men believe in cause and effect.

0개의 댓글