📜  Java中的超级关键字(1)

📅  最后修改于: 2023-12-03 15:16:34.312000             🧑  作者: Mango

Java中的超级关键字

在Java程序设计中,超级关键字具有特殊的用途和含义,不能用于命名标识符。

1. super

Java中的超级关键字super用于引用父类对象或方法,它可以访问父类中的方法和变量。在子类中使用super调用父类中的方法及变量,可以避免与子类中的同名变量或方法冲突。

示例代码
class Animal {
    int age;

    public Animal(int age) {
        this.age = age;
    }

    public void printAge() {
        System.out.println("Animal's age is " + age);
    }
}

class Dog extends Animal {
    String name;

    public Dog(String name, int age) {
        super(age);
        this.name = name;
    }

    public void printDog() {
        super.printAge();
        System.out.println("The dog's name is " + name);
    }
}

public class Test {
    public static void main(String[] args) {
        Dog dog = new Dog("Tom", 3);
        dog.printDog();
    }
}

输出结果为:

Animal's age is 3
The dog's name is Tom
2. this

Java中的超级关键字this代表当前对象的引用,可以用于引用实例变量、实例方法、构造函数等。在方法中访问成员变量时,如果成员变量和局部变量同名,使用this关键字可以明确指出需要访问的是实例的成员变量。

示例代码
public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void print() {
        System.out.println("Name: " + this.name);
        System.out.println("Age: " + this.age);
    }
}

public class Test {
    public static void main(String[] args) {
        Person person = new Person("Lucy", 18);
        person.print();
    }
}

输出结果为:

Name: Lucy
Age: 18
3. final

Java中的超级关键字final表示不可变的常量,一旦声明后,不能被修改。常常用于声明常量、防止类被继承、防止方法被重写等。

示例代码
public class Constant {
    public static final double PI = 3.14159265358979323846;
    public static final int MAX_VALUE = 100;

    public static void main(String[] args) {
        System.out.println(PI);
        System.out.println(MAX_VALUE);
    }
}

输出结果为:

3.141592653589793
100
4. abstract

Java中的超级关键字abstract用于声明抽象类和抽象方法。抽象类不能被实例化,只能被继承,而抽象方法没有具体的实现,必须被子类实现。

示例代码
abstract class Shape {
    abstract double getArea();

    abstract double getPerimeter();
}

class Circle extends Shape {
    double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getArea() {
        return Math.PI * Math.pow(radius, 2);
    }

    public double getPerimeter() {
        return 2 * Math.PI * radius;
    }
}

public class Test {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        System.out.println("Area of circle is " + circle.getArea());
        System.out.println("Perimeter of circle is " + circle.getPerimeter());
    }
}

输出结果为:

Area of circle is 78.53981633974483
Perimeter of circle is 31.41592653589793
5. static

Java中的超级关键字static表示静态的,可以修饰成员变量、方法、代码块等。静态的成员变量被所有对象共享,只在类加载时初始化一次,而不是每次创建对象时都初始化一遍。

示例代码
public class Student {
    static String name;
    int score;

    public Student(int score) {
        this.score = score;
    }

    public static void setName(String name) {
        Student.name = name;
    }

    public void print() {
        System.out.println(name + "`s score is " + score);
    }
}

public class Test {
    public static void main(String[] args) {
        Student.setName("Lucy");
        Student s1 = new Student(90);
        Student s2 = new Student(80);
        s1.print(); // Output: Lucy`s score is 90
        s2.print(); // Output: Lucy`s score is 80
    }
}

输出结果为:

Lucy`s score is 90
Lucy`s score is 80
6. synchronized

Java中的超级关键字synchronized用于实现同步,保证多个线程访问共享数据时的顺序和正确性。使用synchronized关键字可以将一段代码块或方法声明为同步方法。

示例代码

以下示例展示了使用synchronized关键字实现线程同步的方式:

class Counter {
    private int count;

    public synchronized void increment() {
        count++;
    }

    public synchronized void decrement() {
        count--;
    }

    public synchronized int getCount() {
        return count;
    }
}

class IncrementThread extends Thread {
    private Counter counter;

    public IncrementThread(Counter counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            counter.increment();
        }
    }
}

class DecrementThread extends Thread {
    private Counter counter;

    public DecrementThread(Counter counter) {
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            counter.decrement();
        }
    }
}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        IncrementThread incrementThread = new IncrementThread(counter);
        DecrementThread decrementThread = new DecrementThread(counter);
        incrementThread.start();
        decrementThread.start();
        incrementThread.join();
        decrementThread.join();
        System.out.println("Count: " + counter.getCount()); // Output: Count: 0
    }
}

上述代码中,Counter类的三个方法都使用了synchronized关键字,确保多个线程访问时的顺序和正确性。启动多个线程对计数器进行加减操作后,最终输出的计数值为0。

7. extends

Java中的超级关键字extends用于实现继承。子类可以继承父类的成员变量和方法,同时还可以扩展自己的成员变量和方法。

示例代码
class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    public void eat() {
        System.out.println(name + " is eating.");
    }
}

class Dog extends Animal {
    int age;

    public Dog(String name, int age) {
        super(name);
        this.age = age;
    }

    public void bark() {
        System.out.println(name + " is barking.");
    }
}

public class Test {
    public static void main(String[] args) {
        Dog dog = new Dog("Tom", 3);
        dog.eat();
        dog.bark();
    }
}

输出结果为:

Tom is eating.
Tom is barking.
8. implements

Java中的超级关键字implements用于实现接口。一个类可以实现多个接口,同时需要实现每个接口中定义的方法。

示例代码
interface ICalculator {
    double calculate(double x, double y);
}

class Add implements ICalculator {
    public double calculate(double x, double y) {
        return x + y;
    }
}

class Subtract implements ICalculator {
    public double calculate(double x, double y) {
        return x - y;
    }
}

public class Test {
    public static void main(String[] args) {
        ICalculator add = new Add();
        System.out.println(add.calculate(1.0, 2.0));
        ICalculator subtract = new Subtract();
        System.out.println(subtract.calculate(1.0, 2.0));
    }
}

输出结果为:

3.0
-1.0
9. interface

Java中的超级关键字interface用于定义接口。接口是一种抽象的类型,它只定义了方法签名、常量等抽象信息,没有具体实现。接口可以被实现,以实现多态、代码重用等功能。

示例代码
interface IPrintable {
    void print();
}

class Print implements IPrintable {
    public void print() {
        System.out.println("Hello, world!");
    }
}

public class Test {
    public static void main(String[] args) {
        IPrintable print = new Print();
        print.print(); // Output: Hello, world!
    }
}
10. try-catch-finally

Java中的超级关键字trycatchfinally用于异常处理。try后面的代码块被认为是有可能发生异常的代码,在执行过程中如果抛出了异常,则会跳转到catch代码块中进行异常处理,finally代码块中的代码不管是否发生了异常都会执行。

示例代码
public class Test {
    public static void main(String[] args) {
        try {
            int a = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Divisor cannot be zero.");
        } finally {
            System.out.println("This is finally block.");
        }
    }
}

运行结果为:

Divisor cannot be zero.
This is finally block.