[Java/자바] abstraction, access modifiers

sbj·2023년 11월 27일

Java

목록 보기
8/15
post-thumbnail

A Class and Methods

abstractkeyword is a non-access modifier, used for classes and methods:

  • Abstract class(추상 클래스): is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
    객체를 생성할 수 없다. 추상 클래스에 접근하기 위해서는 다른 클래스로부터 상속받아야 한다.

  • Abstract method(추상 메소드): can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
    추상 클래스 내에서만 사용될 수 있다. body가 없다 ‘{ }’.

이렇게 사용된다.

Examples

public class Main {
	public static void main(String[] args) {

//		Vehicle vehicle = new Vehicle();
		Car car = new Car();
		car.go();
	}
}
public abstract class Vehicle {
	
	abstract void go();
}
public class Car extends Vehicle{

	@Override
	void go() {
		System.out.println("The driver is driving the car");
	}
}

Access Modifiers (접근제한자)

  • public
  • protected
  • private
  • no modifier
ModifierClassPackageSubclassWorld
publicOOOO
protectedOOOX
privateOXXX
no modifierOOXX

Example

Package Hierarchy Structure

public

A - package modifier1;
public class A {
	public static void main(String[] args) {
		C c = new C();
		System.out.println(c.publicMessage);
	}
}
C - package modifier2;
*public* class C {
	public String publicMessage = "This is public";
	String defaultMessage = "This is the default";
}
  • public class C
    • 패키지1의 A클래스에서 public String publicMessage에 접근이 가능하다.
*class* C {
	public String publicMessage = "This is public";
	String defaultMessage = "This is the default";
}
  • class C
    • 패키지1의 A클래스에서 public String publicMessage에 접근이 불가능하다.

protected

A - package modifier1;
public class A {
	protected String protectedMessage ="This is protected";
}
Asub extends A - package modifier2;
public class Asub extends A {
	public static void main(String[] args) {
		Asub asub = new Asub();
		System.out.println(asub.protectedMessage);
	}
}

Even though they are located in different packages, Asub extends A. Therefore, Asub can access A's protected attribute. Why? Because is accessible within the class, package, and subclass.

  • 다른 패키지에 위치해있으나, Asub가 A에 extends한다.
    • Asub → A 클래스의 protected에 접근이 가능하다. 왜? protected는, class, package, Subclass 까지 Yes 이다.

private

A - package modifier1;
public class A {
	public static void main(String[] args) {	
	B b = new B();
	System.out.println(b.privateMessage); //Error
	}
}
B - package modifier1;
public class B {
	private String privateMassage = "This is private";
}

An error occurs when trying to access 'private' within the same 'modifier1' package. Why? Because 'private' can only be accessed within the class.

  • 동일한 modifier1 패키지 내에서 private 호출하려고 하면 Error 발생한다.
    • 왜? private는 Class 내에서만 접근 가능하기 때문이다.
profile
Strong men believe in cause and effect.

0개의 댓글