This article is an article for me to go back to the beginning and study Java again. I will post it in several parts. I hope you can see it if you are free.
environment: jdk:JavaSE8 Editor: VS Code
-Frequently used Java data types -Access modifier
The following are the ones I often use. I will explain each of them.
Literal.java
public class Literal {
public byte byteValue = 1;
protected short shortValue = 1;
int intValue = 1;
private long longValue = 1L;
public float floatValue = 1.0F;
public double doubleValue = 1.0;
public char charValue = '1';
public boolean booleanValue = true;
public String strValue = "1";
}
Roughly, the data is handled in the following categories.
Model name | Data to handle |
---|---|
byte、short、int、long | integer |
float 、double | Decimal |
char | Unicode |
String | String |
In addition, these data types are primitive types (basic data types) other than String. String is called a reference type, and each ** Primitive type: Holds the value itself ** ** Reference type: Holds where the value is ** There is a difference in method arguments and processing results. ** Also, all data types other than the above except String are treated as reference types. ** **
Of the above source code ・ Public ・ Protected ・ Default (nothing is attached) ・ Private Is applicable.
By attaching it, you can control the access from other classes to the variable (method).
Access modifier | Access range |
---|---|
public | Accessable from anywhere |
protected | It can be accessed if it is a subclass of the class that defines the variable declared protected. It can be accessed regardless of inheritance if it is in the same package. |
default | Only accessible within the same package |
private | Only accessible from inside the class that defines the variable declared private |
The access level becomes stricter from top to bottom. By using this rule Add private to prohibit direct rewriting of variables in the class, Allow access to variables only by manipulating public methods You can use a technique called ** encapsulation **.
Literal.java
public class Literal {
public byte byteValue = 1;
protected short shortValue = 1;
int intValue = 1;
private long longValue = 1L;
}
class TestLiteral {
public static void main(String[] args) {
Literal l = new Literal();
System.out.println(l.byteValue); //Accessable because it is public
System.out.println(l.intValue);//Accessable because it is the same package
System.out.println(l.shortValue);//Accessable because it is the same package
System.out.println(l.longValue);//Compile error, inaccessible from other classes
}
}
We will continue to improve the quality and update the content of the articles as appropriate. Thank you.
※Source code https://github.com/mamoru12150927/JavaQitta.git
Recommended Posts