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

sbj·2023년 11월 28일

Java

목록 보기
9/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


Example

public class Main {
	public static void main(String[] args) {
		Car car = new Car("쉐보레", "Camero",2010);	
		car.getYear();
		car.setYear(2030);
		System.out.println(car.getYear());		
	}
}
public class Car {

	private String make;
	private String model;
	private int year;

	//Constuctor
	Car(String make, String model, int year){
		this.make = make;
		this.model = model;
		this.year = year;
	}

public String getMake() {
		return make;
	}

	public void setMake(String make) {
		this.make = make;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}	

}

Getter & Setter

  • 변수에 접근하려는 어떤 클래스든, GetterSetter를 통과해야 한다.

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

Interfaces (인터페이스)

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

인터페이스는

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

Class vs Interfaces

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

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(); 
}
profile
Strong men believe in cause and effect.

0개의 댓글