class
- Java application basics
- Combining classes to compose an app
Modifier
- Keywords that determine the nature of classes and members
- Class modifier
- ** public **: accessible from all classes
- ** final **: Do not allow inheritance
- ** abstract **: Abstract class
- ** strictfp **: Floating point arithmetic in an environment-independent way
public
- ** Access modifier **: Current class can be accessed by all classes
- If not specified, only access from the same package (package private)
strictfp
- Floating point numbers under the strictfp operator are ** always processed by the IEEE754 standard **
- ** The same result can be obtained regardless of the environment! ** **
- cf: BigDecimal class if you want to eliminate the error of floating point itself
Class structure
- Class
- Static members
- Class field
- static initialization block
- Class methods
- Instance members
- Field
- Initialization block
- Constructor
- Method
field
- Member variables: Information that should be managed by the class
- Variable naming convention
- Access with
.
Person.java
//String type name,int type age field definition
public class Person {
public String name;
public int age;
}
Main.java
public class Main {
public String firstName;
public String lastName;
public static void main(String[] args) {
//Instantiate with new operator
var p1 = new Person();
p1.name = "Yamada Taro";
p1.age = 30;
var p2 = new Person();
p2.name = "Ichiro Suzuki";
p2.age = 25;
System.out.printf("%s(%d years old)\n", p1.name, p1.age); //Taro Yamada (30 years old)
System.out.printf("%s(%d years old)\n", p2.name, p2.age); //Ichiro Suzuki (25 years old)
}
}
Field modifier
- Generally limited access using privatete
- You do not have to be aware of how to hold data when using the class
- ** public **: Accessable from all classes
- ** protected **: Current class and derived class, only the same package can be accessed
- ** private **: Only accessible from the current class, default value
- ** static **: Declare class field
- ** final **: Reassignment prohibited
- ** transient **: Excluded from serialization
- ** volatile **: Value cache suppression
Field default
- Has a default value depending on the data type of the field
- If you use the default value as it is, you do not have to initialize it, but it lacks readability.
- cf: Method declaration variables (local variables) have no default value
- boolean:false
- byte, short, int, long:0
- float, double:0.0
- char:\u0000
- ** Reference type **: null
Method
- ** Represents class behavior, processing, and behavior **
- ** Manipulate class data values (fields) **
- main method: App entry point, autorun at startup
- Other general methods are called and executed from other methods with the
.
operator.
Person.java
//show method definition
public class Person {
public String name;
public int age;
public String show() {
return String.format("%s(%d).", this.name, this.age);
//return String.format("%s(%d).", name, age);
}
}
MethodBasic.java
//p.Access show method with show
public class MethodBasic {
public static void main(String[] args) {
var p = new Person();
p.name = "Yamada Taro";
p.age = 30;
System.out.println(p.show());
}
}
Method argument
- ** Actual argument **: Passed by the caller
- ** Formal argument **: Recipient variable
- Only accessible from within the method (local variable)
//Actual argument
getBmi(60,1.7)
//Formal argument
public double GetBmi {double weight, double height){
return weight / (height * height )
}
- If there are many arguments, ** group related arguments into a class **
- Argument order
- From the important ones
- Consistency in order
- Related arguments are close
Method return value
- Return the processing result with return
- Instructions after return are not executed
- Optional if there is no return value, ** Specify viod as the method definition type **
- It is possible to explicitly return the process to the caller with
return;
even with the void method.
Person.java
public class Person {
public String name;
public int age;
public void show() {
System.out.printf("%s(%d).\n", this.name, this.age);
}
}
MethodVoid.java
public class MethodVoid {
public static void main(String[] args) {
var p = new Person();
p.name = "Yamada Taro";
p.age = 30;
p.show();
}
}
Method modifier
- With modifiers, you don't have to worry about how to hold data when using a class.
- ** public **: Accessable from all classes
- ** protected **: Current class and derived class, only the same package can be accessed
- ** private **: Only accessible from the current class, default value
- ** static **: Declare class method
- ** abstract **: Declare an abstract method
- ** final **: Override prohibited
- ** synchronized **: Only accessible from one thread
- ** strictfp **: Calculate floating point to be environment independent
- ** native **: Methods written in languages other than Java (C / C ++)
*
public final native void notify();
- There are also disadvantages such as the existence of overhead and more complicated source management than Java alone.
this
- ** Point to the current object **
- Variables that can be used implicitly under the method
- See the name / age field that belongs to the current object
System.out.printf ("% s (% d years old). \ N ", this.name, this.age);
- Method reference
this.myMethod (…)
- Whether to write this
- For fields ** Use this to distinguish between local variables with the same name when covered **
- It seems that it is better to add this to all fields ** so that you do not have to judge whether there are local variables one by one **
- Use this when the method ** wants to specify that it belongs to the current object **
Method overload
- Overload: ** Define multiple methods with the same name but different argument types / sequences **
- Not possible if the return type / argument name is different
- Basically, fields with the same name must not exist in the same class
- But the method is identified by ** signature (name, argument type, list) **, so it is only allowed if the following are different:
- Number of arguments
- Argument data type
- Signature
- ʻInt indexOf (String str, int index) `signature
- Overload
public static int abs( int a )
public static float abs( float a )
- Used when calling the original overload by preparing only the specified value of the argument with one overload
- Note: Overloading with the same number of arguments but different types is not good
- Overloads are selected at compile time, not run time
- When the code below is executed, only the
public void show (CharSequence cs) {
of the for loop type CharSequence
is executed.
//Expect optimal overload depending on the type
//But the result is
//CharSequence: Spring is Akebono
//CharSequence: Summer is night
//CharSequence: Autumn is dusk
public class OverloadAnti {
public void show(String value) {
System.out.println("String: " + value);
}
public void show(StringBuilder builder) {
System.out.println("StringBuilder:" + builder);
}
public void show (StringBuffer buf) {
System.out.println("StringBuffer:" + buf);
}
public void show(CharSequence cs) {
System.out.println("CharSequence:" + cs);
}
}
public class OverloadAntiClient {
public static void main(String[] args) {
var c = new OverloadAnti();
var list = new CharSequence[] {
"Spring is Akebono",
new StringBuilder("Summer is night"),
new StringBuffer("Autumn is dusk"),
};
for (var cs : list) {
c.show(cs);
}
}
}
scope
- ** Variable scope in code **
- Determine where the variable can be referenced
- Depends on where the variable is declared
- ** Field scope **
- Declared directly under class {…}
- Accessable for the entire class
- ** Local variable scope **
- Declared in method definition block
- Only accessible within the method
- ** Block scope **
- A type of local variable
- Declaration under method (control block such as if / while / for)
- Only accessible within the block
Field-local variable collision
- When a variable with the same name is declared inside or outside the method
- ** Variables with different scopes (field variables, local variables) have the same name but are different! !! ** **
- Use ** this ** if you want to access hidden field variables
Scop.java
//data is covered
public class Scope {
//Data as a field variable
public String data = "field";
public String show() {
//Data as a local variable
//Declaring this temporarily hides field variables that should be valid for the entire class
var data = "local";
return data;
//If you want to access hidden field variables
// return this.data;
}
}
ScopeBasic.java
public class ScopeBasic {
public static void main(String[] args) {
var s = new Scope();
//show method local variables
System.out.println(s.show()); //local
//Local variables do not affect field variables
System.out.println(s.data); //field
}
}
- ** Note: The scope of the variable is from the declared position to the end of the block **
- Variables are valid from the declared position
//NG example: str1 is valid from the declared position
public class ScopeStrict {
String str2 = str1; //Str2 cannot be declared before str1
String str1 = “neko desu“;
}
- ** Exceptions to references from methods / constructors **
- Regardless of the declaration position ** Can be referenced from the entire class **
- Cannot be referenced from other than method / constructor (initialization block, etc.)
public class ScopeStrict {
public void show() {
System.out.println(str); //neko desu
}
String str = “neko desu”;
}
StrictClient.java
public class StrictClient {
public static void main(String[] args) {
var s = new ScopeStrict();
s.show();
}
}
Block scope
- Variables declared in control syntax (such as if / while / for / try)
- Because it is a type of local variable, ** a block scope variable with the same name as a higher-level local variable cannot be declared **
- It is possible to declare a local variable with the same name after destroying a block variable
- Block scope variable declaration is also possible with parallel blocks
public class ScopeBlock {
public static void main(String[] args) {
/*
//Declare a block scope variable with the same name as a local variable
var data = "Local scope";
{
var data = "Block scope"; //error
}
*/
{
var data = "Block scope";
}
//At this point the block scope variable has been destroyed
var data = "Local scope"; //OK
System.out.println(data);
}
}
//Parallel block scope
public class ScopeBlock {
public static void main(String[] args) {
{
var data = "Block scope";
System.out.println(data);
}
{
var data = "Block scope 2";
System.out.println(data);
}
}
}