>  기사  >  Java  >  Java의 비 액세스 한정자

Java의 비 액세스 한정자

王林
王林원래의
2024-08-30 15:59:18458검색

비액세스 수정자는 클래스의 동작, 메소드 또는 변수 등에 대해 JVM에 알리기 위해 Java 7에 도입된 키워드입니다. 이는 변수를 두 번 초기화할 수 없음을 나타내는 데 사용되는 final 키워드와 같은 추가 기능을 도입하는 데 도움이 됩니다. 총 7개의 비접근 수식자가 도입되었습니다.

  1. 정적
  2. 최종
  3. 초록
  4. 동기화
  5. 일시적
  6. 엄격한
  7. 네이티브

Java의 비액세스 수정자 유형

다음은 Java의 비액세스 수정자의 유형입니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

1. 최종 비접근 수정자

이 수정자는 다음과 함께 적용될 수 있습니다.

  1. 수업
  2. 방법
  3. 인스턴스 변수
  4. 지역변수
  5. 메서드 인수

Java의 비 액세스 한정자

  • Final Class: Final 키워드는 다른 클래스에 의한 상속을 제한하려는 클래스와 함께 사용됩니다. 예를 들어 최종 클래스 Honda가 있는 경우 이 클래스를 확장하려고 하면 컴파일 타임 오류가 발생할 수 있습니다.

코드:

final class Honda{
public void myFun1(){
System.out.println("Honda Class");
}
}
class Bike extends Honda{
public void myFun1(){
System.out.println("Bike Class");
}
}

출력:

Java의 비 액세스 한정자

  • 최종 메소드: 최종 키워드는 이 메소드가 하위 클래스에서 재정의되지 않음을 Java Runtime Environment에 나타내는 데 사용됩니다.

코드:

class Honda{
public final void myFun1(){
System.out.println("Honda Class");
}
}
class Bike extends Honda{
public void myFun1(){
System.out.println("Bike Class");
}
}

출력:

Java의 비 액세스 한정자

  • 최종 변수: final 키워드는 변수 값에 대한 수정을 제한하기 위해 변수와 함께 사용됩니다. 따라서 JVM이 이를 상수로 처리하도록 나타냅니다. 이는 최종 변수가 한 번만 초기화될 수 있음을 의미합니다.

2. 추상 비액세스 수정자

Java의 비 액세스 한정자

  • 추상 클래스: 클래스는 추상으로 선언되어 이 클래스를 인스턴스화할 수 없음을 나타냅니다. 즉, 이 클래스에 대해 어떤 객체도 형성할 수 없지만 상속될 수 있음을 의미합니다. 하지만 이 클래스에는 하위 클래스의 생성자 내부에서 호출되는 생성자가 있습니다. 여기에는 추상 메서드와 최종 메서드가 포함될 수 있으며, 여기서 추상 메서드는 하위 클래스에서 재정의됩니다.

코드:

public abstract class MyActivity{
public MyActivity(){
}
public final String myFun1(){
}
}
  • 추상 메서드: 추상 메서드는 정의가 없는 메서드입니다. 여기에는 메소드의 시그니처만 포함되어 있으며 서브클래스에서 이를 재정의해야 함을 나타냅니다.

예: public abstract void fun1();

코드:

abstract class Electronics
{
abstract void display();
abstract void display(String msg);
}
class Computers extends Electronics
{
@Override
void display() {
System.out.println("Abstract method is called");
}
@Override
void display(String txt) {
System.out.println(txt);
}
}
public class AbstractDemo {
public static void main(String[] args) {
Computers obj=new Computers();
obj.display();
obj.display("Method with arguments");
}
}

출력:

Java의 비 액세스 한정자

3. 동기화된 비접근 수정자

Java의 비 액세스 한정자

이 키워드는 여러 스레드가 동시에 하나의 메서드에 액세스하는 것을 방지하여 멀티스레딩 기능을 사용하여 프로그램의 흐름을 동기화하고 원하는 결과를 이끌어내는 데 도움이 됩니다.

코드:

class Person1
{
public synchronized void sendFun(String txt)
{
System.out.println("Sending message\t" + txt );
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
System.out.println("\n" + txt + "Sent");
}
}
class DemoThread extends Thread
{
private String txt;
Person1  person;
DemoThread(String m,  Person1 obj)
{
txt = m;
person = obj;
}
public void run()
{
synchronized(person)
{
person.sendFun(txt);
}
}
}
public class HelloWorld
{
public static void main(String args[])
{
Person1 snd = new Person1();
DemoThread S1 =
new DemoThread( " Hi " , snd );
DemoThread S2 =
new DemoThread( " Bye " , snd );
S1.start();
S2.start();
// wait for threads to end
try
{
S1.join();
S2.join();
}
catch(Exception e)
{
System.out.println("Interrupted");
}
}
}

출력:

Java의 비 액세스 한정자

4. 정적 비액세스 수정자

Java의 비 액세스 한정자

이 변수는 메모리 관리에 사용되며 클래스를 로드할 때 가장 먼저 참조되는 변수입니다. 이러한 구성원은 클래스 수준에서 처리됩니다. 따라서 객체를 사용하여 호출할 수 없습니다. 대신 클래스 이름을 사용하여 이를 참조합니다.

  • Static Variable: If a variable is declared as static, then only a single copy of the variable is created and shared among all the objects. Thus any change made to the variable by one object will be reflected in other others. Therefore,  the variables that hold value on the class level is declared as static.
  • Static Class: Static keyword can only be used with nested classes.
  • Static Methods: Since Static Methods are referenced by class name thus can only access static member variables and other static methods. Also, these methods cannot be referred to using this or super pointer. The main method is the most common example of a static method that always get loaded while its class is being loaded.
  • Static Block: This is said to be a block being used to perform certain operations while class is being loaded. Since it is static thus can use only static members of the class.

Code:

public class Demo
{
// static variable
static int x = 10;
static int y;
//static class
public static class DemoInnerClass{
static int z=10;
}
// static block
static {
System.out.println("Static block initialized.");
y = x + 4;
}
//static method
public static void main(String[] args)
{
System.out.println("from main");
System.out.println("Value of x : "+x);
System.out.println("Value of y : "+y);
System.out.println("Value of z : "+DemoInnerClass.z);
}
}

Output:

Java의 비 액세스 한정자

5. Native Non Access Modifier

Java의 비 액세스 한정자

The native keyword is used only with the methods to indicate that the particular method is written in platform -dependent. These are used to improve the system’s performance, and the existing legacy code can be easily reused.

Note: Static, as well as abstract methods, cannot be declared as native.

Example: Consider a function myfun1 in class NativeDemo that is written in C++. To use this code, we will create a link library mylib1 and load it using the class’s static block.

public class DateTimeUtils {
public native String getSystemTime();
static {
System.loadLibrary("nativedatetimeutils");
}
}

6. Strictfp Non-Access Modifier

Java의 비 액세스 한정자

  • Strictfp Class / Method: This keyword is used to ensure that results from an operation on floating-point numbers brings out the same results on every platform. This keyword can not be used with abstract methods, variables or constructors as these need not contain operations.

Code:

public class HelloWorld
{
public strictfp double calSum()
{
double n1 = 10e+07;
double n2 = 9e+08;
return (n1+n2);
}
public static strictfp void main(String[] args)
{
HelloWorld t = new HelloWorld ();
System.out.println("Result is -" + t.calSum());
}
}

Output:

Java의 비 액세스 한정자

7. Transient Non-Access Modifier

While transferring the data from one end to another over a network, it must be serialised for successful receiving of data, which means convert to byte stream before sending and converting it back at receiving end. To tell JVM about the members who need not undergo serialization instead of being lost during transfer, a transient modifier comes into the picture.

Syntax:

private transient member1;

Code:

import java.io.*;
class Demo implements Serializable
{
int x = 10;
transient int y = 30;
transient static int z = 40;
transient final int d = 50;
public static void main(String[] args) throws Exception
{
Demo input = new Demo();
FileOutputStream tos = new FileOutputStream("abc.txt");
ObjectOutputStream tin = new ObjectOutputStream(tos);
tin.writeObject(input);
FileInputStream fis = new FileInputStream("abc.txt");  ObjectInputStream ois = new ObjectInputStream(fis);
Demo output = (Demo)ois.readObject();
System.out.println("x = " + output.x);
System.out.println("y = " + output.y);
System.out.println("z = " + output.z);
System.out.println("d = " + output.d);
}
}

Output:

Java의 비 액세스 한정자

Conclusion

Non-access modifiers are the type of modifiers that tell JVM about the behavior of classes, methods, or variables defined and prepared accordingly. It also helps in synchronizing the flow as well as displaying similar results from operations being performed irrespective of the platform used for execution.

Recommended Article

This is a guide to Non Access Modifiers in Java. Here we discuss the Types of Non Access Modifiersand their methods and code implementation in Java. You can also go through our other suggested articles to learn more –

  1. Layout in Java
  2. Java Compilers
  3. Merge Sort In Java
  4. Java BufferedReader

위 내용은 Java의 비 액세스 한정자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.