亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Java Modifiers
Access control modifier
默認(rèn)訪問(wèn)修飾符-不使用任何關(guān)鍵字
私有訪問(wèn)修飾符-private" >私有訪問(wèn)修飾符-private
公有訪問(wèn)修飾符-public
受保護(hù)的訪問(wèn)修飾符-protected
訪問(wèn)控制和繼承
非訪問(wèn)修飾符
static 修飾符
final 修飾符
abstract 修飾符
synchronized 修飾符
transient 修飾符
volatile 修飾符
Home Java JavaBase What does private mean in java

What does private mean in java

Nov 24, 2022 pm 06:27 PM
java private

In Java, private means "private" and is an access control modifier used to modify classes, properties and methods. Class members modified with private can only be accessed and modified by the methods of the class itself, and cannot be accessed and referenced by any other class (including subclasses of the class); therefore, the private modifier has the highest level of protection.

What does private mean in java

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

Java Modifiers

The Java language provides many modifiers, which are mainly divided into the following two categories:

  • Access modification Symbol
  • Non-access modifier

Modifier is used to define classes, methods or variables, and is usually placed at the front of the statement. We use the following example to illustrate:

public?class?ClassName?{
???//?...
}
private?boolean?myFlag;
static?final?double?weeks?=?9.5;
protected?static?final?int?BOXWIDTH?=?42;
public?static?void?main(String[]?arguments)?{
???//?方法體
}

Access control modifier

In Java, you can use access control modifiers to protect classes, variables, and methods and constructor access. Java supports 4 different access rights.

  • default (i.e. default, write nothing): Visible within the same package, no modifiers are used. Use objects: classes, interfaces, variables, methods.

  • private (Private) : Visible within the same class. Use objects: variables, methods. Note: Classes (external classes) cannot be modified

  • ##public: Visible to all classes. Used objects: classes, interfaces, variables, methods

  • protected: Visible to classes and all subclasses in the same package. Use objects: variables, methods. Note: Classes (external classes) cannot be modified.

We can illustrate access permissions through the following table:

Access ControlModifierCurrent classIn the same packageDescendant classes (same package)Descendant classes (different packages)Other packagesYYYYY YYYYNYYY NNYNNNN

默認(rèn)訪問(wèn)修飾符-不使用任何關(guān)鍵字

使用默認(rèn)訪問(wèn)修飾符聲明的變量和方法,對(duì)同一個(gè)包內(nèi)的類是可見(jiàn)的。接口里的變量都隱式聲明為?public static final,而接口里的方法默認(rèn)情況下訪問(wèn)權(quán)限為?public。

如下例所示,變量和方法的聲明可以不使用任何修飾符。

實(shí)例

String?version?=?"1.5.1";
boolean?processOrder()?{
???return?true;
}

私有訪問(wèn)修飾符-private

私有訪問(wèn)修飾符是最嚴(yán)格的訪問(wèn)級(jí)別,所以被聲明為?private?的方法、變量和構(gòu)造方法只能被所屬類訪問(wèn),并且類和接口不能聲明為?private。

聲明為私有訪問(wèn)類型的變量只能通過(guò)類中公共的 getter 方法被外部類訪問(wèn)。

Private 訪問(wèn)修飾符的使用主要用來(lái)隱藏類的實(shí)現(xiàn)細(xì)節(jié)和保護(hù)類的數(shù)據(jù)。

下面的類使用了私有訪問(wèn)修飾符:

public?class?Logger?{
???private?String?format;
???public?String?getFormat()?{
??????return?this.format;
???}
???public?void?setFormat(String?format)?{
??????this.format?=?format;
???}
}

實(shí)例中,Logger 類中的 format 變量為私有變量,所以其他類不能直接得到和設(shè)置該變量的值。為了使其他類能夠操作該變量,定義了兩個(gè) public 方法:getFormat() (返回 format的值)和 setFormat(String)(設(shè)置 format 的值)

公有訪問(wèn)修飾符-public

被聲明為 public 的類、方法、構(gòu)造方法和接口能夠被任何其他類訪問(wèn)。

如果幾個(gè)相互訪問(wèn)的 public 類分布在不同的包中,則需要導(dǎo)入相應(yīng) public 類所在的包。由于類的繼承性,類所有的公有方法和變量都能被其子類繼承。

以下函數(shù)使用了公有訪問(wèn)控制:

public?static?void?main(String[]?arguments)?{
???//?...
}

Java 程序的 main() 方法必須設(shè)置成公有的,否則,Java 解釋器將不能運(yùn)行該類。

受保護(hù)的訪問(wèn)修飾符-protected

protected 需要從以下兩個(gè)點(diǎn)來(lái)分析說(shuō)明:

  • 子類與基類在同一包中:被聲明為 protected 的變量、方法和構(gòu)造器能被同一個(gè)包中的任何其他類訪問(wèn);

  • 子類與基類不在同一包中:那么在子類中,子類實(shí)例可以訪問(wèn)其從基類繼承而來(lái)的 protected 方法,而不能訪問(wèn)基類實(shí)例的非protected修飾的方法。

protected 可以修飾數(shù)據(jù)成員,構(gòu)造方法,方法成員,不能修飾類(內(nèi)部類除外)。

接口及接口的成員變量和成員方法不能聲明為 protected。 可以看看下圖演示:

子類能訪問(wèn) protected 修飾符聲明的方法和變量,這樣就能保護(hù)不相關(guān)的類使用這些方法和變量。

下面的父類使用了 protected 訪問(wèn)修飾符,子類重寫(xiě)了父類的 openSpeaker() 方法。

class?AudioPlayer?{
???protected?boolean?openSpeaker(Speaker?sp)?{
??????//?實(shí)現(xiàn)細(xì)節(jié)
???}
}
?
class?StreamingAudioPlayer?extends?AudioPlayer?{
???protected?boolean?openSpeaker(Speaker?sp)?{
??????//?實(shí)現(xiàn)細(xì)節(jié)
???}
}

如果把 openSpeaker() 方法聲明為 private,那么除了 AudioPlayer 之外的類將不能訪問(wèn)該方法。

如果把 openSpeaker() 聲明為 public,那么所有的類都能夠訪問(wèn)該方法。

如果我們只想讓該方法對(duì)其所在類的子類可見(jiàn),則將該方法聲明為 protected。

protected 是最難理解的一種 Java 類成員訪問(wèn)權(quán)限修飾詞,更多詳細(xì)內(nèi)容請(qǐng)查看?Java protected 關(guān)鍵字詳解。

訪問(wèn)控制和繼承

請(qǐng)注意以下方法繼承的規(guī)則:

  • 父類中聲明為 public 的方法在子類中也必須為 public。

  • 父類中聲明為 protected 的方法在子類中要么聲明為 protected,要么聲明為 public,不能聲明為 private。

  • 父類中聲明為 private 的方法,不能夠被繼承。


非訪問(wèn)修飾符

為了實(shí)現(xiàn)一些其他的功能,Java 也提供了許多非訪問(wèn)修飾符。

static 修飾符,用來(lái)修飾類方法和類變量。

final 修飾符,用來(lái)修飾類、方法和變量,final 修飾的類不能夠被繼承,修飾的方法不能被繼承類重新定義,修飾的變量為常量,是不可修改的。

abstract 修飾符,用來(lái)創(chuàng)建抽象類和抽象方法。

synchronized 和 volatile 修飾符,主要用于線程的編程。

static 修飾符

  • 靜態(tài)變量:

    static 關(guān)鍵字用來(lái)聲明獨(dú)立于對(duì)象的靜態(tài)變量,無(wú)論一個(gè)類實(shí)例化多少對(duì)象,它的靜態(tài)變量只有一份拷貝。 靜態(tài)變量也被稱為類變量。局部變量不能被聲明為 static 變量。

  • 靜態(tài)方法:

    static 關(guān)鍵字用來(lái)聲明獨(dú)立于對(duì)象的靜態(tài)方法。靜態(tài)方法不能使用類的非靜態(tài)變量。靜態(tài)方法從參數(shù)列表得到數(shù)據(jù),然后計(jì)算這些數(shù)據(jù)。

對(duì)類變量和方法的訪問(wèn)可以直接使用?classname.variablename?和?classname.methodname?的方式訪問(wèn)。

如下例所示,static修飾符用來(lái)創(chuàng)建類方法和類變量。

public?class?InstanceCounter?{
???private?static?int?numInstances?=?0;
???protected?static?int?getCount()?{
??????return?numInstances;
???}
?
???private?static?void?addInstance()?{
??????numInstances++;
???}
?
???InstanceCounter()?{
??????InstanceCounter.addInstance();
???}
?
???public?static?void?main(String[]?arguments)?{
??????System.out.println("Starting?with?"?+
??????InstanceCounter.getCount()?+?"?instances");
??????for?(int?i?=?0;?i?<?500;?++i){
?????????new?InstanceCounter();
??????????}
??????System.out.println("Created?"?+
??????InstanceCounter.getCount()?+?"?instances");
???}
}

以上實(shí)例運(yùn)行編輯結(jié)果如下:

Starting?with?0?instances
Created?500?instances

final 修飾符

final 變量:

final 表示"最后的、最終的"含義,變量一旦賦值后,不能被重新賦值。被 final 修飾的實(shí)例變量必須顯式指定初始值。

final 修飾符通常和 static 修飾符一起使用來(lái)創(chuàng)建類常量。

實(shí)例

public?class?Test{
??final?int?value?=?10;
??//?下面是聲明常量的實(shí)例
??public?static?final?int?BOXWIDTH?=?6;
??static?final?String?TITLE?=?"Manager";
?
??public?void?changeValue(){
?????value?=?12;?//將輸出一個(gè)錯(cuò)誤
??}
}

final 方法

父類中的 final 方法可以被子類繼承,但是不能被子類重寫(xiě)。

聲明 final 方法的主要目的是防止該方法的內(nèi)容被修改。

如下所示,使用 final 修飾符聲明方法。

public?class?Test{
????public?final?void?changeName(){
???????//?方法體
????}
}

final 類

final 類不能被繼承,沒(méi)有類能夠繼承 final 類的任何特性。

實(shí)例

public?final?class?Test?{
???//?類體
}

abstract 修飾符

抽象類:

抽象類不能用來(lái)實(shí)例化對(duì)象,聲明抽象類的唯一目的是為了將來(lái)對(duì)該類進(jìn)行擴(kuò)充。

一個(gè)類不能同時(shí)被 abstract 和 final 修飾。如果一個(gè)類包含抽象方法,那么該類一定要聲明為抽象類,否則將出現(xiàn)編譯錯(cuò)誤。

抽象類可以包含抽象方法和非抽象方法。

實(shí)例

abstract?class?Caravan{
???private?double?price;
???private?String?model;
???private?String?year;
???public?abstract?void?goFast();?//抽象方法
???public?abstract?void?changeColor();
}

抽象方法

抽象方法是一種沒(méi)有任何實(shí)現(xiàn)的方法,該方法的的具體實(shí)現(xiàn)由子類提供。

抽象方法不能被聲明成 final 和 static。

任何繼承抽象類的子類必須實(shí)現(xiàn)父類的所有抽象方法,除非該子類也是抽象類。

如果一個(gè)類包含若干個(gè)抽象方法,那么該類必須聲明為抽象類。抽象類可以不包含抽象方法。

抽象方法的聲明以分號(hào)結(jié)尾,例如:public abstract sample();

實(shí)例

public?abstract?class?SuperClass{
????abstract?void?m();?//抽象方法
}
?
class?SubClass?extends?SuperClass{
?????//實(shí)現(xiàn)抽象方法
??????void?m(){
??????????.........
??????}
}

synchronized 修飾符

synchronized 關(guān)鍵字聲明的方法同一時(shí)間只能被一個(gè)線程訪問(wèn)。synchronized 修飾符可以應(yīng)用于四個(gè)訪問(wèn)修飾符。

實(shí)例

public?synchronized?void?showDetails(){
.......
}

transient 修飾符

序列化的對(duì)象包含被 transient 修飾的實(shí)例變量時(shí),java 虛擬機(jī)(JVM)跳過(guò)該特定的變量。

該修飾符包含在定義變量的語(yǔ)句中,用來(lái)預(yù)處理類和變量的數(shù)據(jù)類型。

實(shí)例

public?transient?int?limit?=?55;???//?不會(huì)持久化
public?int?b;?//?持久化

volatile 修飾符

volatile 修飾的成員變量在每次被線程訪問(wèn)時(shí),都強(qiáng)制從共享內(nèi)存中重新讀取該成員變量的值。而且,當(dāng)成員變量發(fā)生變化時(shí),會(huì)強(qiáng)制線程將變化值回寫(xiě)到共享內(nèi)存。這樣在任何時(shí)刻,兩個(gè)不同的線程總是看到某個(gè)成員變量的同一個(gè)值。

一個(gè) volatile 對(duì)象引用可能是 null。

實(shí)例

public?class?MyRunnable?implements?Runnable
{
????private?volatile?boolean?active;
????public?void?run()
????{
????????active?=?true;
????????while?(active)?//?第一行
????????{
????????????//?代碼
????????}
????}
????public?void?stop()
????{
????????active?=?false;?//?第二行
????}
}

通常情況下,在一個(gè)線程調(diào)用 run() 方法(在 Runnable 開(kāi)啟的線程),在另一個(gè)線程調(diào)用 stop() 方法。 如果?第一行?中緩沖區(qū)的 active 值被使用,那么在?第二行?的 active 值為 false 時(shí)循環(huán)不會(huì)停止。

但是以上代碼中我們使用了 volatile 修飾 active,所以該循環(huán)會(huì)停止。

更多相關(guān)知識(shí),請(qǐng)?jiān)L問(wèn)常見(jiàn)問(wèn)題欄目!

public
protected
default
private

The above is the detailed content of What does private mean in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

See all articles