찾다
Javajava지도 시간Java의 비 액세스 한정자
Java의 비 액세스 한정자Aug 30, 2024 pm 03:59 PM
java

비액세스 수정자는 클래스의 동작, 메소드 또는 변수 등에 대해 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으로 문의하세요.
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

归纳整理JAVA装饰器模式(实例详解)归纳整理JAVA装饰器模式(实例详解)May 05, 2022 pm 06:48 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于设计模式的相关问题,主要将装饰器模式的相关内容,指在不改变现有对象结构的情况下,动态地给该对象增加一些职责的模式,希望对大家有帮助。

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구