[Introduction to Java] I tried to summarize the knowledge that I think is essential

Introduction

Last time I wrote an article "I'm interested in web programming so I'll study", but this time it's Java: sunglasses: I had been studying Java for more than two years in a university class, but I didn't understand it at all, so I summarized only the necessary parts as a notebook. I also wrote about object-oriented programming in this article, but I think this is important because it ** leads to an understanding of object-oriented programming in PHP and JavaScript. Well then, thank you: information_desk_person:

Class declaration

A class is a collection of processes required to execute a program. Write the beginning of the word and the delimiter in capital letters as nouns. The state and behavior of the class are defined in the execution process part. The way to write it is as follows.

class class name{
Execution processing...
}

In Java, one file and one class are the principle. In the following, it is written so that there are multiple classes in one file, but please separate when actually writing the code. (Why only 1 public class in Java file)

About member variables (fields)

A member variable defines the state of a class, and can declare basic type, class type, and array type variables. The declaration order of member variables is qualifier type variable name. Basic type: ʻint id; Class type:Test a = new Test; Array type: ʻint a [];or ʻint [] a;<br> Member variables include class variables and instance variables. Class variables are types withstaticin front of them. Instance variables are variables withoutstatic`.


public class Test{
    int id = 1; //Member variable (instance variable)
    static int value = 200; //Member variables (class variables)

    void student(){ //This is a method
        System.out.println(id);
        System.out.println(value);
    }
}

Also, member variables can be referenced from any method or constructor that attempts to reference the state of that class. However, local variables, which are variables that define the state of each method and constructor, can only be referenced from within each method and constructor.


public class Student{
    int grade = 1; //Member variables
    void student1(){
        int id_1 = 7; //Local variables
        System.out.println(grade); //Can be referenced because it is a member variable
        System.out.println(id_1); //Can be referenced because it is a local variable declared in student1
        System.out.println(id_2); //Since it is a local variable declared in student2, it cannot be referenced.
    }
    void student2(){
        int id_2  = 1000;
        System.out.println(grade); //Can be referenced because it is a member variable
        System.out.println(id_1); //Since it is a local variable declared in student1, it cannot be referenced.
    }
}

Method

A method defines the behavior within a class. It consists of the following formats.

Modifier Return value data type Method name (argument type argument name)....){
Method body
}

① Return value data type

The return value is the value to be returned to the caller of the method. If no value is returned (no return value), it is described as void type. An example is written below.


public class Return {
    public static void print() {  //Since it is a void type, it does not return a return value
        System.out.println("It all returns to nothing");
    }
    public static int add(int x) {
        int result = x + 1999;
        return result;  //The return statement returns the value of result.
    }

    public static void main(String[] args) {
        int result = add(1); //Specify the variable with the same type as the value returned by return for clarity
        print(); //Output "It all returns to nothing"
        System.out.println(result); //Output as "2000"
    }
}

② Argument

Describe the argument when it is necessary to inherit the value in the method. How to write is (argument type formal argument name ....) The argument type represents the type of the value to be inherited, and the formal argument name represents the variable name that can be referenced only in the method. If there is no value to inherit, only () is used. The method to read the method with arguments is method name (value 1, value 2, ...);, and when read, the name changes from ** formal argument ** to ** actual argument **.


public class Argument {
    public static void  main(String[] args){
        rabbithouse("Kafu Chino"); //← Actual argument
        rabbithouse("Hoto Shinai");
        rabbithouse("Riyo Tenzenza");
        amausaan("Chiya Ujimatsu");
        fleur_du_lapin("Saji Kirima");
    }
    public static void rabbithouse(String name){ //← Formal argument
        System.out.println("Rabbit house:"+ name);
    }
    public static void amausaan(String name){
        System.out.println("Kantoan:" + name);
    }
    public static void fleur_du_lapin(String name){
        System.out.println("Fleur de La Pan:" + name);
    }
}

The execution result looks like this.

Rabbit house:Kafu Chino
Rabbit house:Hoto Shinai
Rabbit house:Riyo Tenzenza
Kantoan:Chiya Ujimatsu
Fleur de La Pan:Saji Kirima

Modifier

There are the following types of Java modifiers. (I've omitted quite a bit)

① Access modifier

public: No restrictions, can be referenced from anywhere protected: Only accessible from the same class, within the same package, or its subclasses private: Can be referenced only from the same class. Member variables are often "private" to learn from encapsulation. None: Say package private. It can be freely accessed only from inside the package with the access modifier omitted.

②static Indicates that it is a class variable. You can access it without instantiating the class, so you can access it with class name.member name.

③final If you declare it on a class, you will not be able to inherit the class. Also, if you attach it to a method, you will not be able to override the method in your subclass.

About instances and objects

From here, I will touch on object orientation. Think of a class as a blueprint, an object as an object (such as a human or a car), and an instance as an entity created based on a blueprint. .. ..
The instance is created in the following format. Class name variable name = new class name (argument); There are two ways to refer to an instance. Variable name.Member variable name; Variable name.Method name;

** Updated June 8 ** In Java, there is a naming convention that all member variables (fields) and method names are all lowercase, and in the case of compound characters, the delimiter is uppercase. It is said that it is called camel case, but he commented that this is a general description method. .. !! In the following, the variable name is set as "A" etc., but it is not common, so I would appreciate it if you could complete it ...: bow_tone1:

An example is written below.


class Instance {
    String name = "Shiratsuyu-class destroyer "Yudachi""; //Member variables

    void shipType(){ //Method
        System.out.println("Destroyer");
    }
}

class MainClass{
    public static void main(String[] args) {
        Instance A = new Instance();
        System.out.println(A.name); //Here, output as "Shiratsuyu-class destroyer" Yudachi ""
        A.shipType(); //Output "destroyer" here
    }
}

static and non-static

I mentioned a little about the member variables (fields) and modifiers above, but I will explain them in more detail here.

Methods and variables with static are referred to in various ways in reference books and on the net, such as static method, static method, class method, and class variable. Don't get messed up: fearful: Conversely, methods and variables that do not have static are called instance methods, non-static methods, and instance variables.

static method

Since a static method is a method of a class, it can be called by other static methods, instance methods, or another class without creating an instance using ** new **. However, when calling in your own class, method name (); is fine, but when calling in another class, it must be class name.method name ();. Also, static methods will be shared and used by that class. Therefore, the process does not change no matter where you call it, so if there is a common process or data in the design, the static method is good.

Instance method

A method identified for each object instantiated using the new operator. Therefore, ** you must always create and call an instance. ** **

Summary


class Method1 {

    //static method, static method, class method
    static void staticMethod1() {

        // instanceMethod();This is no good!You cannot (directly) access instance methods (in the same class) from static methods.

        Method1 a = new Method1(); //Instantiate a class
        a.instanceMethod(); //You can access instance methods with indirect access through the instance.
    }

    //static method / static method
    static void staticMethod1_1() {
        staticMethod1(); //You don't need the class name because it is called from within your own class.

        Method1.staticMethod1(); //You can still call it.
    }

    //Instance method / non-static method
    void instanceMethod() {
        staticMethod1(); //Call static method from instance method(access)Also ok without class name

        Method1.staticMethod1(); //You can still call it.
    }
}

//Another class
class Method2 {
    static void staticMethod2() {

        // staticMethod1();This is no good!

        Method1.staticMethod1(); //When calling from another class, the class name.static method name

        // instanceMethod();This is no good!

        Method1 b  = new Method1(); //When accessing an instance method of another class, access the instance method through the instance
        b.instanceMethod();

        Method2 c = new Method2(); //Access to instance methods in your class is the same.
        c.instanceMethod2();
    }

    void instanceMethod2() {
        Method1.staticMethod1_1(); //A class name is required when calling a static method of another class from an instance method!
        staticMethod2();
        Method3.staticMethod3();
    }
}

class Method3 extends Method1{
    static void staticMethod3() {
        staticMethod1(); //When inherited, it can be called without the need for a class name

        //instanceMethod();This is not good for inheritance. Be sure to instantiate the class and access through it

        Method1 d = new Method1();
        d.instanceMethod();
    }

    void instanceMethod3() {
        staticMethod1();
    }
}

constructor

A constructor is executed when an instance of a class is created, and it is a process that allows you to determine the value of a member variable and initialize it. To call the constructor, the method with the same class name as when the instance was created with class name variable name = new class name (argument); is the constructor **. In other words, it can also be expressed as class name variable name = new constructor name (argument).


public class Constructor1{
    String name = "Aoyama Blue Mountain";

    public Constructor1(){
        System.out.println(name);
    }
}
class Main{
    public static void main(String[] args) {
        Constructor1 cs = new Constructor1();
    }
}

The execution result is as follows.

Aoyama Blue Mountain

public class Constructor2{
    public Constructor2(String str){
        System.out.println(str);
    }
}
class Main{
    public static void main(String[] args){
        Constructor2 A = new Constructor2("Hello");
    }
}

The execution result is as follows.

Hello

About this

① This that points to your own instance variable or instance method

Use this when the variable name of a member variable (field) and a local variable are the same. If this is not added, the local variable defined in the method will take precedence, so the member variable (field) will not be referenced.


class ThisClass{
    private int number;
    public void setNumber(int number){ //Local variables(argument)The value of number is a member variable(Fold)Is assigned to the number of
        this.number = number + 100;
    }
    public int getNumber(){
        return this.number;
    }
}

class Main{
    public static void main(String[] args) {
        ThisClass A = new ThisClass();
        A.setNumber(1);
        System.out.println(A.getNumber()); //It is output as 101.
    }
}

When compared with the Student class written in the above heading "About member variables (fields)", with or without this depending on whether the variable names of the member variables (fields) and local variables are the same. Please judge.

② Call another constructor from the constructor this ()

Use this () when you want to describe common processing in only one constructor and call that processing from another constructor. It is different from the one written in ①.


class ThisConstructor {
    private String ShopName;
    private String CharacterName;

    public ThisConstructor(String shopName , String CharacterName){
        this.ShopName = shopName;
        this.CharacterName = CharacterName;
    }

    //Setting the default value
    public ThisConstructor(){
        this("Rabbit house" , "Kafu Chino");
    }

    //Field initialization
    public void print(){
        System.out.println(ShopName+" : "+CharacterName);
    }
}

class Main{
    public static void main(String[] args) {
        ThisConstructor tc1 = new ThisConstructor();
        tc1.print();

        ThisConstructor tc2 = new ThisConstructor("Rabbit house" , "Riyo Tenzenza");
        tc2.print();
    }
}

Referenced site

-[Introduction to Java] Use the return value of a method in the return statement (explain multiple return values) -From basic Java constructor syntax to good usage -[Introduction to Java] What is this? I will explain the meaning and usage of Kihon! -Java Road

Recommended Posts

[Introduction to Java] I tried to summarize the knowledge that I think is essential
I tried to summarize Java learning (1)
I tried to summarize Java 8 now
I tried to summarize the basics of kotlin and java
I tried to summarize the methods used
I tried to summarize Java lambda expressions
I tried to summarize the Stream API
What is Docker? I tried to summarize
I tried to summarize the words that I often see in docker-compose.yml
I tried to summarize the methods of Java String and StringBuilder
[Ruby] I tried to summarize the methods that frequently appear in paiza
[Ruby] I tried to summarize the methods that frequently appear in paiza ②
I tried to summarize again the devise that was difficult at first sight
I tried to summarize the state transition of docker
I tried to make FizzBuzz that is uselessly flexible
I tried to implement the Euclidean algorithm in Java
I tried to make a program that searches for the target class from the process that is overloaded with Java
I tried to summarize the basic grammar of Ruby briefly
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to explain the method
I tried the Java framework "Quarkus"
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
I tried to summarize what was asked at the site-java edition-
[Ruby] Tonight, I tried to summarize the loop processing [times, break ...]
Special Lecture on Multi-Scale Simulation: I tried to summarize the 5th
I tried to translate the error message when executing Eclipse (Java)
I tried to understand how the rails method "redirect_to" is defined
Special Lecture on Multi-Scale Simulation: I tried to summarize the 8th
I tried to understand how the rails method "link_to" is defined
[Java] I tried to make a maze by the digging method ♪
I tried to move the Java compatible FaaS form "Fn Project"
I tried to display the calendar on the Eclipse console using Java.
Special Lecture on Multi-Scale Simulation: I tried to summarize the 7th
Introduction to java for the first time # 2
I tried the new era in Java
I tried to implement the Iterator pattern
Output of the book "Introduction to Java"
I went to the Java Women's Club # 1
I tried to summarize the key points of gRPC design and development
I tried to solve the past 10 questions that should be solved after registering with AtCoder in Java
I tried to summarize about JVM / garbage collection
I tried to make Basic authentication with Java
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to organize the session in Rails
I tried to implement deep learning in Java
Initialize Ruby array with 0 like Java, that is, set the default value to 0
[Must see !!!] I tried to summarize object orientation!
[Java] Introduction to Java
I tried to output multiplication table in Java
[JavaScript] The strongest case when I tried to summarize the parts I do not understand
I tried to set tomcat to run the Servlet.
Introduction to java
I tried to create Alexa skill in Java
[Small story] I tried to make the java ArrayList a little more convenient
I tried to break a block with java (1)
I tried to summarize the points to consider when acquiring location information with the iOS application ③
I tried to summarize the points to consider when acquiring location information with the iOS application ①
The story that did not disappear when I tried to delete mysql on ubuntu
[Introduction to Java] List of things that got caught by the 14th day of programming
I tried to summarize the points to consider when acquiring location information with the iOS application ②