Java beginner escape boot camp Part 1 Java class structure and how to write

For everyone who started studying Java as a new employee I would like to update it irregularly.

The theme this time is "How to write a class".

Uninflected word of class

First, the basic form of the class. As an example, consider a class that represents a "person."


public class Person {

  /**Full name*/
  private String name;

  /**age*/
  private int age;

  /**
   *constructor
   * @param name full name
   * @param age age
   */
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
  /** 
   *Getting age
   */
  public int getAge() {
    return this.age;
  }

  /**
   *Get one year old
   */
  public void countUpAge() {
    this.age++;
  }

  /**
   *Self-introduction
   */
  public void introduction() {
    System.out.println("Hello, I" + this.name + ", " + this.age + "I'm old.");
  }
}

Elements that make up the class

Not limited to the classes introduced this time Classes are roughly divided into three sections.


public class name{
  
field

constructor

Method

}

field

In the Person class, it refers to the following parts.

  /**Full name*/
  private String name;

  /**age*/
  private int age;

Fields are ** variables ** that can be used anywhere in the class. In other words, you can refer to the same variable from different methods within the same class.

constructor

In the Person class, it refers to the following part.

  /**
   *constructor
   * @param name full name
   * @param age age
   */
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

By the way, when initializing this Person class, the code will be as follows.

Person person = new Person("Taro", 10);

In this way, the constructor is used to perform certain actions at the start.

Since the constructor is always called when initializing the object, It is often used to set field values.

Method

In the Person class, it refers to the following part.


  /** 
   *Getting age
   */
  public int getAge() {
    return this.age;
  }

  /**
   *Get one year old
   */
  public void countUpAge() {
    this.age++;
  }

  /**
   *Self-introduction
   */
  public void introduction() {
    System.out.println("Hello, I" + this.name + ", " + this.age + "I'm old.");
  }

The process to be executed is described in the method.

Method Kihon

The method is used to combine one process.

You can put all the processing together, It's easier for people to see if you divide each procedure separately.

You can give the method a name, so It is important to divide them properly according to the purpose and variables to be handled.

Basic writing

The basic form of the method is as follows.

Access modifier Return type Method name(Argument 1,Argument 2, ...) {

processing

return Return value;
}

Do you remember hearing the word "function" during math time?

f(x) = x + 1

If this is converted to a Java method, the description will be as follows.

public void func(x) {
  return x + 1;
}

Both are "return by adding 1 to the argument x".

In fact, "methods" and "functions" are very close to each other and refer to almost the same thing. For example, in C language, the following description is called a function.

int func(x) {
  return x + 1;
}

In Java and other object-thinking languages, the description of a function described in a class is called a method.

I would like to discuss the exact difference between functions and methods at another time.

Access modifier

Access modifiers define the extent to which a field or method can be accessed. It is specified as public or private.

If public is given, it will be accessible from outside the class, With prvate, you can only access it from within that class.

Return value

As an example, in the following case, a method called ** getAge ** that returns ** int (numerical value) ** is defined.

public int getAge() {
  return this.age;
}

By specifying the type of this return value, the caller of this method is You can recognize that "this method returns an int type".

//You can get the age of person like this
int himAge = person.getAge();

//This will result in a type mismatch and an error
String himAge = person.getAge();

If there is no return value

If there is no return value, set the character "void" in the return value part. void means "empty / nothing".

If void is specified for the return value, no value is returned, so it is not necessary to describe return.

  /**
   *Get one year old
   */
  public void countUpAge() {
    this.age++; 
    //You can omit the "return" that should be here.
  }

Arguments and overloads

Now, let's add a "method to set the name".

The name has a surname and a given name, and may have a middle name. Let's create a name setting method corresponding to each.

/**
 *First and last name support method
 * @param lastName Last name
 * @param firstName first name
 */
public void setName(String lastName, String firstName) {
  this.name = lastName + " " + firstName;
}

/**
 *Method for middle name
 * @param lastName Last name
 * @param firstName first name
 * @param middleName middle name
 */
public void setName(String lastName, String firstName, String middleName) {
  this.name = firstName + "・" + middleName + "・" + lastName;
}

Now let's do each of these.

person.setName("Sato", "Taro");
// ->"Taro Sato"

person.setName("Sato", "Christina", "Taro");
// ->"Taro, Christina, Sato"

In this way, you can do different things with the same method named "setName".

This is called ** "method overloading" **.

Overloads can be used when you have multiple arguments for the same purpose.

at the end

I think there are quite a few people who say, "I don't understand because there are so many things in the class."

However, there aren't many rules to remember.

The source code will be easier to read just by dividing it into the three elements introduced this time.

Without trying to read everything suddenly Isn't it the first step toward understanding to think separately little by little?

Recommended Posts

Java beginner escape boot camp Part 1 Java class structure and how to write
Java Beginner Escape Boot Camp Part 2 Understanding Java Classes and Encapsulation
[Java] How to output and write files!
[Java] How to use FileReader class and BufferedReader class
[Java] How to use Calendar class and Date class
[Java] Types of comments and how to write them
How to use java class
How to call and use API in Java (Spring Boot)
How to write and notes when migrating from VB to JAVA
How to disassemble Java class files
How to decompile java class files
[Java] How to use LinkedHashMap class
How to write Java variable declaration
How to use class methods [Java]
[Java] How to use Math class
Basics of Java development ~ How to write programs (variables and types) ~
Kotlin Class part.2 to send to Java developers
[Java] How to use the File class
[Java] How to use the HashMap class
[Introduction to Java] How to write a Java program
[Java] Inheritance and structure of HttpServlet class
[Processing × Java] How to use the class
How to use Java Scanner class (Note)
[Java] How to use the Calendar class
How to write and explain Dockerfile, docker-compose
JDBC promises and examples of how to write
Basics of Java development ~ How to write a program (flow and conditional branching) ~
Java Development Basics ~ How to Write Programs * Exercise 1 ~
[Java] How to get and output standard input
How to get Class from Element in Java
How to convert a solidity contract to a Java contract class
How to get and study java SE8 Gold
[Java] Memo on how to write the source
How to write Java String # getBytes in Kotlin?
How to access Java Private methods and fields
[Java] How to use compareTo method of Date class
How to write Scala from the perspective of Java
How to write a unit test for Spring Boot 2
java: How to write a generic type list [Note]
Write a class in Kotlin and call it in Java
Java memory management and how to read GC Viewer
How to convert A to a and a to A using AND and OR in Java
How to create and execute method, Proc, Method class objects
How to write modern Java. Immutable Java, consider Null safety.
How to use and apply Java's JFrame / Canvas class
How to write Rails
How to write dockerfile
How to write docker-compose
How to write Mockito
Class and instant part2
How to write migrationfile
Java programming (class structure)
How to write comments in the schema definition file in GraphQL Java and reflect them in GraphQL and GraphQL Playground
How to get the class name / method name running in Java
Java conditional branching: How to create and study switch statements
Difference between Java and JavaScript (how to find the average)
What is the LocalDateTime class? [Java beginner] -Date and time class-
[Java] Set structure of collection class (about HashSet and TreeSet)
Comparison of how to write Callback function (Java, JavaScript, Ruby)
[Processing × Java] How to use loop 2 --- Nested structure, coordinate conversion
What happened in "Java 8 to Java 11" and how to build an environment