Home  >  Article  >  Java  >  What are the important keywords in Java

What are the important keywords in Java

PHPz
PHPzforward
2023-05-25 17:16:061575browse

    1.extends

    • is used for class inheritance, usage: class Subclass nameextends Parent class name{}

    class Animal{}//父类
    class cat extends Animal{}//子类用extends实现继承

    Note: A class can only declare inheritance using the extends keyword A parent class

    • # is used for interface inheritance interface, usage: interface interface nameextends interface name{}

    interface Clippers {}
    interface Warriors {}
    interface Lakers extends Clippers,Warriors {}//接口类用extends关键字继承其他接口(可多个)

    Note:

    • The interface cannot be declared to inherit from other classes

    • Interfaces can only inherit other
    • interfaces

      using the extends declaration, and can inherit multiple interfaces

    • When a class implements an interface using
    • implements

      , it must not only implement the methods of the interface, but also implement the methods inherited by the interface Interface methods

    • 2.implements

      are used to declare that a class implements an
    • interface class

      , Usage: class Class nameimplements Interface name{}

      class Nets implements Clippers,Warriors{}//用implements关键字声明实现了两个接口类
    Note:

      A
    • ordinary class

      can implementskeyword declarationimplement multiple interfaces, but must implement all methods in all interfaces

    • Abstract class

      To implement the interface, you don’t need to implement the method of the interface (because there can be abstract methods in the abstract class)

    • Meaning:

      You can use the implements keyword to declare multiple interfaces to achieve something like multiple inheritance

    • 3.final

    Usage method:

      Modify the
    • class

      so that the class cannot be inherited

    • Modify the
    • method

      so that the method cannot be overridden by subclasses (it can still be inherited and called )

    • Modify the
    • attribute

      so that the value of the attribute cannot be modified (make it a constant)

    • Modify
    • local variable

      so that the variable cannot be modified (local constant)

    Usage details:

    final

    The modified attributes must be assigned an initial value when defined, and cannot be modified. The initial value can be assigned at the following location

    • When defined (explicit initialization)

    • In the constructor

    • In a code block

    • ##static final
    : global constant

    if
      final
    • The modified attribute is static (

      static), then cannot assign an initial value in the constructor. Reason: Static properties require initialization when the class is loaded value, and the constructor is only called when creating the object, so it may result in calling the static property without creating the object and not assigning the value to the static property

    • final
    • cannot modify

      constructor method, it is meaningless

      is modified by
    • final
    • and

      static at the same time The attribute will not cause the class to be loaded when called, and is more efficient 4.native

    Basic introduction :

    native is used to modify the

    method

    . The modified method becomes an interface called by Java but implemented by non-Java code (native Method), this method can be implemented externally in any language"A native method is a java method whose implementation is provided by non-java code."

    Usage method:

    nativeThe position of the modified method must be before the method

    return type

    , and the method There is no requirement to access the modifier position, such as: public native int hashCode();##nativeDetails:

    native

    Method
      has no method body
    • , and no

      {}##modified with native Method

      cannot be modified with
    • abstract

      because abstract indicates that the method has no implementation body, while the native method has The implementation body is only implemented in non-Java code. The return type of the native method can be any type

    • If a class with a native method is inherited

      , the
    • subclass will inherit this
    • native method, and can be rewritten in java using JNI (Java Native Interface ) Interacting with other languages

      JNIJava平台的一部分,它允许Java代码和其他语言写的代码进行交互。

      What are the important keywords in Java

      使用步骤:

      • 编写带有native方法的java类,生成.java文件

      • 使用javac命令编译生成.class文件

      • 使用javah -jni 类名 生成.h文件

      • 使用C/C++(或者其他编程语言)实现native方法,创建.cpp(或其他)文件

      • C/C++编写的文件创建动态链接库(生成DLL文件)

      • native方法中使用System.loadLibrary()方法加载动态库,将DLL文件名作为参数传入,这时候再运行.java程序即可实现对本地方法的调用

      详细步骤参考

      native意义:

      Java无法直接访问到操作系统底层(如系统硬件),但通过使用native关键字修饰方法可以借用其他的语言来扩展Java程序的功能,提高程序的效率

      5.static

      修饰变量,成为静态变量或者类变量

      • 使用方法:访问修饰符+``static``+数据类型+变量名

      注意事项:

      • 静态变量会被类的所有对象实例共享,并且在类加载的时候就会初始化。

      • 静态变量的访问方法(遵守相关访问权限):类名.静态变量名 或者 对象名.静态变量名

      修饰方法,成为静态方法或者类方法

      • 使用方法:访问修饰符+``static``+返回数据类型+方法名+{}

      注意事项:

      • 调用方法(遵守相关访问权限):类名.静态方法名 或者 对象名.静态方法名

      • 静态方法普通方法都是随着类加载而加载,将结构信息存储在方法区

      • 静态方法中不允许使用thissuper关键字

      • 静态方法中只能访问静态变量静态方法

      • 普通方法可以访问静态成员和普通成员

      • 修饰代码块,成为静态代码块

      静态代码块会在类加载时被加载,优先级和静态属性一样,有多个静态代码块和静态属性时,初始化顺序按定义顺序执行

      好处:static关键字的使用,将类中的一些成员修饰成静态的,这样我们不需要创建该类的对象就可以调用该成员,大大提高了编程效率

      6.transient

      基本介绍:

      transient用于修饰实现了Serilizable接口的类中的成员变量,在该类的实例对象进行序列化处理时transient修饰的成员变量不会进行序列化

      使用例子:

      import java.io.FileOutputStream;
      
      import java.io.IOException;
      
      import java.io.ObjectOutputStream;
      import java.io.Serializable;
      public class outStream {
          public static void main(String[] args) throws IOException {
              String filePath = "d:\Cat.txt";
              ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
              oos.writeObject(new Cat("小花猫", 3));
              oos.close();
          }
      }
      class Cat implements Serializable {
          private String name;
          private int age; //没有用transient修饰
          public Cat(String name, int age) {
              this.name = name;
              this.age = age;
          }
          @Override
          public String toString() {
              return "Car{" +
      
                      "name='" + name + ''' +
      
                      ", age=" + age +
      
                      '}';
          }
      }
      public class inStream {
          public static void main(String[] args) throws IOException, ClassNotFoundException {
              String filePath = "d:\Cat.txt";
              ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
              System.out.println(ois.readObject());
              ois.close();
          }
      }

      What are the important keywords in Java

      What are the important keywords in Java

      可以在Cat.txt文件内看到两个成员变量都能被序列化,并且能被反序列化读出信息。

      当小花猫觉得自己的年龄是隐私不想被读出时,transient修饰成员变量age:

      ......
      private String name;
      private transient int age; //使用transient修饰
      ......

      What are the important keywords in Java

      What are the important keywords in Java

      这时在Cat.txt文件中可以看到只有name一个成员变量被序列化,反序列化后的成员变量age读出的是int类型的默认值,说明对于transient修饰的成员变量,在类的实例对象序列化的过程中会被忽略

      transient细节

      • transient修饰的成员变量可以理解为:不会参与进行对象的序列化和反序列化过程,生存周期仅存于调用者的内存不会写进磁盘里进行持久化

      • static修饰的成员变量(静态变量)也是不可序列化的,不论被transient修饰与否

      因为序列化是保存的实例对象的状态,而静态变量保存的是类的状态

      • transient关键字只能修饰变量,不能修饰方法和类

      • transient关键字不能修饰局部变量

      • transient关键字修饰的是自定义类的变量,则该类需要实现Serilizable接口

      注意:

      实现Serilizable接口的类的实例对象是自动进行序列化的,如果序列化对象的类实现的是Externalizable接口,则序列化不会自动进行,需要实现接口内的方法指定要序列化的变量,这时与有无Transient修饰无关

      7.synchronized

      基本介绍:

      关键字synchronized可以保证在同一时刻只有一个线程可以执行被synchronized修饰的方法或代码块

      线程同步

      程序中多个线程都要使用同一个方法,而这个方法用synchronized进行了修饰,在多个线程调用这个方法时必须遵循同步机制

      线程同步机制

      当一个线程使用synchronized修饰的方法时,其他线程想使用这个方法时就必须等待,直到这个线程使用完synchronized方法

      synchronized使用方法:

      • 普通同步方法:public synchronized void m () {}

      public class syn implements Runnable {
          static int i = 0;
          public static void main(String[] args) throws InterruptedException {
              syn test = new syn();
              Thread t1 = new Thread(test);
              Thread t2 = new Thread(test);
              t1.start();
              t2.start();
          }
          public synchronized void increase() {//被synchronized修饰的同步方法
              System.out.println(Thread.currentThread().getName() + "调用:" + i++);
      
          }
          @Override
          public void run() {
              for (int j = 0; j < 100; j++) {
                  increase();
              }
          }
      }

      What are the important keywords in Java

      两个线程同时调用一个对象的一个同步方法,由于一个对象只有一把锁,所以只有一个线程能够获得该对象的锁,另一个线程无法获得,就不能调用该对象的synchronized方法,需要等对象被释放后才能调用

      从运行结果中可以证明线程1抢到了锁,线程0必须等待线程1执行完毕,否则不能访问该同步方法。

      • 静态同步方法:public static synchronized void m () {}

      public class syn implements Runnable {
          static int i = 0;
          public static void main(String[] args) throws InterruptedException {
              syn test = new syn();
              syn test1 = new syn();
              Thread t1 = new Thread(test);//传入实例对象test
              Thread t2 = new Thread(test1);//传入实例对象test1
              t1.start();
              t2.start();
          }
          public static synchronized void increase() {//同步静态方法
              System.out.println(Thread.currentThread().getName() + "调用:" + i++);
          }
          @Override
          public void run() {
              for (int j = 0; j < 100; j++) {
                  increase();
              }
          }
      }

      What are the important keywords in Java

      虽然两个线程实例化了两个不同的对象,但是synchronized修饰的是静态方法,两个线程仍然发生了互斥,因为静态方法是依附与类的而不是对象,线程1先抢到了类的锁,而线程0必须等待线程1执行完毕释放才能调用同步方法

      • 同步代码块:synchronized(object) {}

      public class syn implements Runnable {
          static Object object = new Object();//共享对象
          public static void main(String[] args) throws InterruptedException {
              syn test = new syn();
              syn test1 = new syn();
              Thread t1 = new Thread(test);
              Thread t2 = new Thread(test1);
              t1.start();
              t2.start();
      
          }
          @Override
          public void run() {
              synchronized (object) {//代码块用静态成员变量上锁
                  for (int j = 0; j < 100; j++) {
                      System.out.println(Thread.currentThread().getName() + "调用第" + j + "次");
                  }
              }
          }
      }

      What are the important keywords in Java

      同步代码块用两个实例变量共享的静态成员object对象来上锁,虽然是两个线程实例化两个不同的对象,但是对整个syn类来说只有一个共享的object对象,所以只有一把锁,每当有线程来访问代码块时需持有锁,对象锁被其他线程持有时需等待。线程1需要等线程0执行完毕才能访问同步代码块

      同步的局限性:

      由于同步的方法或代码块只能同一时间让一个线程访问,所以会导致程序的执行效率降低

      尽可能synchronized修饰的范围最小化,来减少互斥对程序执行带来的影响

      8.volatile

      基本介绍:

      volatile用于修饰变量,用volatile修饰的变量的值被某个线程修改时,会强制将修改的值立即写入主存中,主存中的值更新会使得缓存中的该变量的值失效,对比与非volatile变量,可能会被其他线程读取到更新前的值。

      使用方法:

      //现在有线程1和线程2同时执行下列代码
      int i = 0;
      i = i + 1;

      执行完毕后预想的结果是 i = 2;但是可能存在这样一种情况:两个线程先同时把i的值读取到自己的工作内存中,然后再分别执行 i = i + 1 的操作,再将结果写入主存,这样两个线程写入的都是 i = 1,最终 i 的结果是 1 ,而不是 2

      但如果 i 是 volatile 修饰的变量就会不一样了,在一个线程修改 i的值后,会立即强制在主存中更新 i 的值,这样会导致另一个线程的工作内存中 i 的缓存值无效,所以另一个线程再次从主存中读取新的 i 的值,这样保证了i的值是最新并正确的

      并发编程的三大概念:

      • 原子性:执行一个操作时,要么全部步骤执行完毕且不被中断,要么就不执行

      x = 100;//是原子性操作
      y = x;//不是原子性操作,可分解为:1.先读取x的值    2.将x的值写入主存
      x ++;//不是原子性操作,可分解为:1.读取x的值    2.进行加一操作    3.写入主存
      • 可见性:多个线程对同一个变量进行操作时,一个线程修改了变量的值,其他线程能立即看到修改的值

      • 有序性:程序执行的顺序按照代码的先后顺序执行

      volatile的意义

      • 保证了不同线程对变量进行修改时的可见性:因为对于volatile变量来说,被修改后新值对其他线程来说是立即可见的

      • 保证了有序性volatile禁止了指令重排,它能保证在对volatile修饰的变量进行操作时,之前的代码语句已经全部被执行,并且后面的语句都未执行,但是对其他语句的顺序是不做保证的

      注意: volatile不能保证原子性,因为不能保证对变量的操作是原子性操作

      9.this

      • 在方法中修饰属性,this理解为当前对象,用来区别成员方法和形参,通常省略

      • 修饰方法,this理解为当前对象,通常省略;不能在静态方法中使用

      • 调用构造器,在构造器中使用this(形参列表)显式调用指定的其他构造器

        • 必须在首行调用其他构造器

        • 一个构造器中不能调用多个其他构造器

        • 不能在构造器中调用递归调用,不能成环调用

      10.super

      super可以理解为:父类的

      • 修饰属性:去父类中找对应属性,用来区分子父类重名的属性

      • 修饰方法:调用重写之前的方法

      • 调用构造器:使用super(形参列表)指定调用父类构造器

        • super(形参列表)必须放在构造器的首行

        • super(形参列表)this(形参列表)只能二选一

        • 在构造器首行如果没有显式声明super(形参列表)this(形参列表)则默认调用父类的空参构造器super()(如果此时父类中没有空参构造器就会报错)

      • 不能在静态方法中使用

      当一个方法和属性被static属性修饰时,这些方法和属性是优先于对象加载进入内存的,是随着类的加载而加载的;this是当前对象的引用,super是指父类的引用,当静态方法加载进内存进栈时,如果在静态方法中有this和super关键字时,this和super也被加载到了内存,但是这个时候并没有对象的引用,this和super没有初始化,所有编译会报错。

      10.1.子类对象实例化的过程

      What are the important keywords in Java

      11. Access modifier

      What are the important keywords in Java

      public modified class:

      • At most in a class There can be a public class, and the file name must be consistent with the public class

      • If there is no public class, the file name can be arbitrary

    The above is the detailed content of What are the important keywords in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete