Java base modifier keyword collation

  • 2020-06-12 08:57:21
  • OfStack

Java - based modifier keyword collation

It's been a while since I became an Java programmer. Recently, I was asked a question about the Java modifier keyword, but I had no idea what it was. So I felt that in addition to the actual programming and algorithms, I also needed to learn these things.

Through Google search, I only got 1 trivial points, not complete. So I wrote this article on this topic. This is also an interview question that can be used to test your knowledge of computer science.

Java modifiers are keywords that you add to variables, classes, and methods to change their meaning. They can be divided into two groups:

Access control modifier Nonaccess modifier

Let's start with some code examples of access control modifiers and how to use them.

修饰符 说明
public 公共可见
private 类可见
protected 包和所有的子类可见

So how do you use these three access control modifiers? Look at the following two classes. Ignore the inefficiencies of the code here, because this is a tutorial.

Create a named project/mypackage/Person java file, and add the following code:


package mypackage;
class Person {
 private String firstname;
 private String lastname;
 protected void setFirstname(String firstname) {
  this.firstname = firstname;
 }
 protected void setLastname(String lastname) {
  this.lastname = lastname;
 }
 protected String getFirstname() {
  return this.firstname;
 }
 protected String getLastname() {
  return this.lastname;
 }
}

The Person class above has the private variable and the protected method. This means that these variables will be accessible only from the class and methods will be accessible only from the mypackage package.

Next create a named project/mypackage/Company java file, and add the following code:


package mypackage;
import java.util.*;
public class Company {
 private ArrayList<Person> people;
 public Company() {
  this.people = new ArrayList<Person>();
 }
 public void addPerson(String firstname, String lastname) {
  Person p = new Person();
  p.setFirstname(firstname);
  p.setLastname(lastname);
  this.people.add(p);
 }
 public void printPeople() {
  for(int i = 0; i < this.people.size(); i++) {
   System.out.println(this.people.get(i).getFirstname() + " " + this.people.get(i).getLastname());
  }
 }
}

The above class is public, so it can be accessed from any class inside and outside the package. It has a private variable that can only be accessed within the class, and a public method for the heap. Since the Person class and the Company class share the same package, the Company class has access to the Person class and all its methods.

To complete the demonstration of the access control modifier, let's create a driver class in a new project/ MainDriver.java file:


import mypackage.*;
public class MainDriver {
 public static void main(String[] args) {
  Company c = new Company();
  c.addPerson("Nic", "Raboy");
  c.printPeople();
  Person p = new Person();
  p.setFirstname("Maria");
  p.setLastname("Campos");
 }
}

Remember, since the Company class is public, we had no problem adding and printing people. However, since the Person class is protected, we get a compile-time error because MainDriver is not part of the mypackage package.

Now let's look at the existing non-access modifiers and some sample code for how to use them.

修饰符 说明
static 用于创建类、方法和变量
final 用于最终确定类、变量和方法的实施方式
abstract 用于创建抽象方法和类
synchronized 用于多线程的同步机制对资源进行加锁,使得在同1个时间,只有1个线程可以进行操作
Volatile 1个变量声明为volatile,就意味着这个变量是随时会被其他线程修改的,因此不能将它cache在线程memory中。

So how do you use these five non-access modifiers?

A good example of the static modifier in Java is:


int max = Integer.MAX_VALUE
int numeric = Integer.parseInt("1234");

In the above example, notice that we used variables and methods from the Integer class rather than instantiating them first. This is because those particular methods and variables are static.

The abstract modifier is slightly different. You can create a class with methods, but they are basically defined. You can't add logic to them. Such as:


abstract class Shape {
 abstract int getArea(int width, int height);
}

Then in the subclass, you can add code like this:


class Rectangle extends Shape {
 int getArea(int width, int height) {
  return width * height;
 }
}

The synchronized and volatile modifiers are described below.

Let's start with the 1 thread example, in which we will access the same method from two different threads:


import java.lang.*;
public class ThreadExample {
 public static void main(String[] args) {
  Thread thread1 = new Thread(new Runnable() {
   public void run() {
    print("THREAD 1");
   }
  });
  Thread thread2 = new Thread(new Runnable() {
   public void run() {
    print("THREAD 2");
   }
  });
  thread1.start();
  thread2.start();
 }
 public static void print(String s) {
  for(int i = 0; i < 5; i++) {
   System.out.println(s + ": " + i);
  }
 }
}

Running the above code will output printing 1 random order. It may be continuous or discontinuous, depending on CPU. However, if we use the synchronized modifier, the first thread must complete before the second thread begins to print. The print(String s) method can look like this:


public static synchronized void print(String s) {
 for(int i = 0; i < 5; i++) {
  System.out.println(s + ": " + i);
 }
}

Next, let's look at an example using the volatile modifier:


import java.lang.*;
public class ThreadExample {
 public static volatile boolean isActive;
 public static void main(String[] args) {
  isActive = true;
  Thread thread1 = new Thread(new Runnable() {
   public void run() {
    while(true) {
     if(isActive) {
      System.out.println("THREAD 1");
      isActive = false;
     }
    }
   }
  });
  Thread thread2 = new Thread(new Runnable() {
   public void run() {
    while(true) {
     if(!isActive) {
      System.out.println("THREAD 2");
      try {
       Thread.sleep(100);
      } catch (Exception e) {
      }
      isActive = true;
     }
    }
   }
  });
  thread1.start();
  thread2.start();
 }
}

Since the volatile variable is a state flag, running the code above prints the number of threads and alternates between them. This is because the flag is stored in main memory. If we remove the volatile keyword, the thread will alternate only once, because with only one local reference, the two threads are essentially invisible to each other.

conclusion

Java modifiers can be a bit tricky to understand, and many programmers aren't really familiar with them. This is a great interview question to ask to test your book knowledge. Finally, if There is anything I have omitted or explained incorrectly, please feel free to point it out.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: