/ W3SCHOOLS

W3schools - Modifier

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

Modifier

Public modifier keyword is an access modifier, meaning that it is used to set the access level for classes, attributes, methods, and constructors

Divide modifiers into two groups

  • Access modifiers

    • controls the access level
  • Non-access modifiers

    • don’t control access level, but provides other functionality

Access modifier

For class

  • public : accessible by any other class

  • default  : accessible by classes in the same package

    • if you don’t specify a modifier

For attribute, method, constructor

  • public : accessible for all classes

  • private : only accessible within the declared class

  • default : only accessible in the same package

  • protected : the code is a accessible in the same package and subclasses

Non-access modifier

For class

  • final : the class can’t be inherited by other classes

  • abstract : the class can’t be used to create objects

    • to access an abstract class, it must be inherited from another class

For attribute, method

  • final : Can’t be overridden/modified

  • static : belongs to the class, rather than an object

  • abstract : can only be used in an abstract class, and can only be used on methods

    • the method doesn’t have a body, the body is provided by the subclass
abstract void run();
  • transient : be skipped when serializing the object containing them

  • synchronized : methods can only be accessed by one thread at a time

  • volatile : the value of an attribute is not cached thread-locally, and is always read from the “main memory”

Encapsulation

Is to make sure that “sensitive” data is hidden from user

  • declare class variable/attributes as private

  • provide public “get” and “set” methods to access and update the value of a private variable

Get and Set

Private variables can only be accessed within the same class

It is possible to access them if we provide public get and set methods

get method

  • return the variable value

set method

  • sets the value

Syntax for both is that

  • start with either “get” or “set”, followed by the name of the variable with the first letter in upper case
		public class Person{
			private String name;
			//getter
			public String getName(){
				return name;
			}
			//setter
			public void setName(String newName){
				this.name = newName;
			}
		}

Why encapsulation?

Better control of class attributes and methods

Can change one part of the code without affecting other parts

Increased security of data