Java 中的 final、abstract、synchronized 非訪問修飾符是什麼?
關鍵詞 abstract 用於宣告抽象方法和抽象類。一旦某個方法被宣告為抽象方法,我們就不應該為那些方法指定內容。一旦某個類被宣告為抽象類,它將無法被例項化。
示例
abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
}
public class AbstractDemo extends Employee{
public AbstractDemo(String name, String address, int number) {
super(name, address, number);
}
public static void main(String [] args) {
Employee e = new AbstractDemo("George W.", "Houston, TX", 43);
System.out.println("
Call mailCheck using Employee reference--");
e.mailCheck();
}
}
輸出
Constructing an Employee Call mailCheck using Employee reference-- Mailing a check to George W. Houston, TX
修飾符 final 可與方法,類和變數相關聯。一旦宣告最終版本,最終類將無法被例項化,最終方法將無法被覆蓋,最終變數將無法被重新分配。
示例
class TestExample {
final int value = 10;
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public final void changeName() {
System.out.println("This is a final method");
}
}
final class Demo{ }
public class FinalExample extends TestExample {
public static void main(String args[]){
FinalExample obj = new FinalExample();
System.out.println(obj.value);
System.out.println(obj.BOXWIDTH);
System.out.println(obj.TITLE);
obj.changeName();
}
}
輸出
10 6 Manager This is a final method
關鍵字 synchronized 用於指示方法只能由一個執行緒同時訪問。同步修飾符可以與四種訪問級別修飾符中的任何一種一起使用。
示例
public class TestThread {
public static Object Lock1 = new Object();
public static Object Lock2 = new Object();
public static void main(String args[]) {
ThreadDemo1 T1 = new ThreadDemo1();
ThreadDemo2 T2 = new ThreadDemo2();
T1.start();
T2.start();
}
private static class ThreadDemo1 extends Thread {
public void run() {
synchronized (Lock1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (Lock2) {
System.out.println("Thread 1: Holding lock 1 & 2...");
}
}
}
}
private static class ThreadDemo2 extends Thread {
public void run() {
synchronized (Lock2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (Lock1) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
}
輸出
Thread 1: Holding lock 1... Thread 2: Holding lock 2... Thread 1: Waiting for lock 2... Thread 2: Waiting for lock 1...
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP