Collect from arrays to object-oriented. Please for review (Not particularly related to the title Krillin)
--The following simple grammar is omitted-- if syntax if-else if-else syntax swith statement while statement do-while statement for statement
Only the same type of data can be stored in each element of the array. (For int, only int, only String, etc.) Subscripts (index) count from 0. (Element 0th ~)
Let's create a String type array.
//Define String type array variable dragonBall
String[] dragonBall;
//Create 7 String type elements and assign them to complete the array dragonBall
dragonBall = new String[7];
//It is also possible to create in one line
String[] dragonBall = new String[7];
Use ** length **.
If you do System.out.println (dragonBall.length);
, 7 will be output.
When substituting a two-star sphere (Arshinchu) for the second (first element) of the array dragonBall
dragonBall [1] =" Two-star ball ";
What if I output an element with nothing assigned to the array?
String[] dragonBall = new String[7];
System.out.println(dragonBall[0]);
↑ null is output and no error occurs. Arrays are automatically initialized just like ints and Strings. ・ Int, double type ⇒ 0 ・ Boolean type ⇒ false ・ String type ⇒ null
There are the following two patterns of description methods.
① int [] score1 = new int [] {20,30,40,50};
⇒ An array of 4 elements is created
② int [] score2 = {20,30};
⇒ An array of two elements is created
Variables can be used as subscripts for arrays.
public class Main {
public static void main(String[] args){
int[] score = {10,20,30};
for(int i =0 ; score.length ; i++){ //4th line
System.out.println(score[i]);
}
}
}
The variable i changes to 0,1,2. This is called ** turning an array **. By using "length" on the 4th line, the number of elements does not change even if the initial value is changed. There is an advantage that no code modification is required.
The extended for statement is convenient when you simply want to rotate all array types.
for (type variable name: array) {}
int[] score = {10,20,30};
for(int value : score){
System.out.println(value);
}
As for the movement, the value of the first week is 10 and the value of the second week is 20. It will rotate by the number of elements.
Take a look at the following code. What is in the output b?
int a = 1;
int b = a;
a = 2;
System.out.println(b);
1 is entered in b. Since it was assigned when a = 1, it does not matter what is assigned to a after that.
However, it changes with an array.
int[] a = {1};
int[] b = a;
a[0] = 2;
System.out.println(b[0]);
2 is entered in b.
The array a does not contain any direct values.
It only knows where the value is. This is called ** reference **.
In int [] b = a;
, the location is shared.
If you compare a place to an address, Mr. A puts a banana in room 101. With B = A, Mr. A tells B the room number. Mr. A adds an apple. When Mr. B goes to Room 101, there are bananas and apples.
Two-dimensional array example
int[][] scores = new int[2][3];
There are two boxes, each containing three boxes.
[0] ⇒ [0][1][2]
[1] ⇒ [0][1][2]
A total of 6 boxes will be prepared.
Exercises.java
public class Main {
public static void main(String[] args){
int[][] scores = {{10,20,30}, {40,50,60}};
System.out.println(scores[1][1]);
System.out.println(scores.length);
System.out.println(scores[0].length);
}
}
}
Execution result.
50
2
3
Creating a method is called ** method definition **.
To use it is called ** calling a method **.
The "{}" part after the method name is called the method block.
It can be called with method name ();
.
public static void main(String[] args){
methodA();
}
public static void methodA(){
System.out.println("Called method A");
}
You can pass a value to the method, which is called a ** argument **. More specifically, the value to be passed is called ** actual argument **, and the value to be received is called ** formal argument **.
The side that passes the argument method name (value);
Argument recipient ~ method name (variable to which argument type argument is assigned) {}
public static void main(String[] args){
methodA("Krillin");
}
public static void methodA(String name){
//The argument krillin is included in the variable name.
System.out.println(name + "Mr. is.");
}
Example:
The side that passes the argument method name (" Krillin ", 20);
Argument recipient ~ method name (String name, int age) {}
Variables declared in a method are called ** local variables **. Local variables are valid only within the method to which the variable belongs. (The effective range is called the scope) It is different from the local variable with the same name declared by another method.
Returning a value is called ** returning a value **.
The data (value) returned is called ** return value **.
return statement ⇒ return Return value; You can return the value with
.
public static return type method name(Type variable){
return Return value;
}
If there is no value to return, change the "return type" part. Make it "void" which means that nothing is returned.
Return value utilization example.java
public static void main(String[] args){
int a = 10;
int b = 20;
int total = tasu(a, b); //Since the return value is returned, substitute it for total
System.out.println("The total is" + total + "is.");
}
//Method to add
public static int tasu(int x, int y){
return x+y;
}
Since the return statement also terminates the method, an error will occur even if code is written after the return statement.
Defining a method with the same name is called ** overload **. Even if the method name is the same, there is no problem even if it is defined if the formal argument type and the number of arguments are different. It will automatically determine when you call the method.
public static int add(String x, int y){
return x+y;
}
public static int add(int x, int y){
return x+y;
}
public static int add(int x, int y,int z){
return x+y+z;
}
If you call add (" Krillin ", 20)
, the top method will be called properly.
Passing the value itself in the sample code so far is called ** passing by value **. Passing an array is called ** passing by reference **.
Reference passing example.java
public class Main {
public static void main(String[] args) {
int[] array = {1,2,3};
//Pass an array (pass by reference).
printArray(array);
}
public static void printArray(int[] array){
for(int element : array){
System.out.println(element);
}
}
}
Reference passing example 2.java
public class Main {
public static void main(String[] args) throws Exception {
int[] array = {1,2,3};
intArray(array);
for(int i : array){
System.out.println(i);
}
}
public static void intArray(int[] array){
for(int i = 0; i < array.length; i++){
array[i]++;
}
}
}
The execution result will be 2,3,4. The value of the array array changes even though it is not returned as a return value Because the array type is a reference type.
By using ** class **, one program can be divided into multiple parts, that is, ** parts **, Development can be shared. As the number of classes increases, it can be further divided into parts using ** packages **. -The first letter of the class name must be uppercase. -The first letter of the package name is basic lowercase. -Since the packages are independent, it is possible to create the same class name for each package. -The dot "." Is often included in the package name. -When using a package other than your own, you need to attach the package you belong to.
Example:
In a certain class of movie package
I want to use the tasu method of the CalcLogic class of the Calc.app package.
int total = calc.app.CalcLogic.tasu(a,b);
A class like this with the package name at the beginning ** full qualified class name ** It is abbreviated as ** FQCN **.
--If you develop it separately for each package, ** name collision ** will not occur even if the class name is shared with others. --It is recommended that the package name is the reverse of the domain. (foo.exsample.com ⇒ com.exsample.foo)
The domain is unaffected by anyone in the world.
import statement: FQCN description can be omitted.
import package name.class name;
The amount of description is reduced as follows.
int total = calc.app.CalcLogic.tasu(a,b);
⇒ int total = CalcLogic.tasu(a,b);
It's hard if you have a lot of classes you want to import.
Use an asterisk when you want to import all classes.
For the calc.app package
import calc.app*;
API
** API ** is like a useful formula.
Import java.util. *
To use automatic sorting with java.util.Arrays.sort ().
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
int[] heights = {20,35,10};
java.util.Arrays.sort(heights);
for(int h : heights){
System.out.println(h);
}
}
}
The execution result will be 10,20,35.
API | meaning |
---|---|
java.lang | Required classes |
java.util | Convenient classes |
java.math | Math classes |
java.net | Internet communication class group |
java.io | File read / write,Data processing classes |
java.lang is imported automatically. You can see the details of various APIs by searching for "Java API Reference".
How to create an object ① Class definition ② Instantiation ③ Completion of instance (object)
If you compare the mechanism of an object with a Gunpla ... ① If you make a basic mold for Gunpla ② Use it to generate various Gunpla ③ Completion If you make the basics, you can easily mass-produce them.
If you compare what you need for a program with an RPG ... ・ Main method (God class, works first) ・ Other methods (character class)
public class Gokuu{
String name;
int hp;
void attack(){・ ・ ・}
void jump(){・ ・ ・}
}
Declaring a variable is called ** attribute definition **. The defined variable is called ** field **. The method declaration is called ** operation definition **.
If you add "final" to the beginning of the field declaration, the value cannot be changed.
When "final" is attached, it is called ** constant field **. Constant fields are easy to understand and uppercase letters are recommended.
final String NAME;
final int HP;
this
public class Gokuu{
String name;
int hp;
void attack(){
this.name = "Goku";
}
}
"This.name =" Goku ";" and "name =" Goku ";" have the same behavior, Unexpected behavior may occur if "name" is also used for local variables and formal parameters. In order to prevent it, ** this ** indicates that it is its own field.
The following is an extreme example Thanks to "this", it is easy to distinguish between formal parameters and fields.
Example of using name as a formal argument.java
public class Main {
public static void main(String[] args) {
//Instance generation (explained later)
Monster m = new Monster();
//Pass the argument "Majin Buu"
m.attack("Majin Buu")
}
}
public class Monster{
String name;
public void attack(String name){
//Assign formal arguments to fields
this.name = name;
System.out.println(this.name + "To attack!")
}
}
Class ⇒ Attribute ⇒ Operation The diagram summarized by these three is called a class diagram. Fields and methods are collectively called ** members **.
** How to create an instance **
Class name variable name = new class name ();
When you want to use the attack method of Goku class in a certain class
It can be used by creating an instance.
Create a "new" instance.
Create an instance of Goku class with new Gokuu ();
.
The variable name is "gokuu1".
Since it is an instance of the Goku class, the type is "Gokuu"
Therefore, Gokuu gokuu1 = new Gokuu ();
.
I also want to use the attack method of the Goku class.
It becomes gokuu1.attack ();
.
If you want to get the HP field of Goku class again
Just write gokuu1.hp;
.
Generation may be divided into two lines
Goku instance generation.java
Gokuu gokuu1; //Class types can also be used for fields.
gokuu1 = new Gokuu();
You can understand it by looking at the code used when explaining "this" again.
Example of using name as a formal argument.java
public class Main {
public static void main(String[] args) {
//Instance generation
Monster m = new Monster();
//Pass the argument "Majin Buu"
m.attack("Majin Buu")
}
}
public class Monster{
String name;
public void attack(String name){
//Assign formal arguments to fields
this.name = name;
System.out.println(this.name + "To attack!")
}
}
Some values are output by the following code.
Gokuu g1 = new Gokuu();
g1.hp = 100;
Gokuu g2;
g2 = g1;
g2.hp = 200;
System.out.println(g1.hp);
The execution result is 200. g1 and g2 refer to the same "new Gokuu ();". (Same as for array.) So if you change the value with g2, the value of g1 will also change. But when you say ** instance independence ** and g2 "new Gokuu ();" by itself, It is not referenced. You can make a copy of the same HP as Goku No. 1, and you can also make a copy of Goku No. 2 with a different HP.
For the time being, Son Goku asks Karin for recovery.
Example.java
public class Main {
public static void main(String[] args) {
Gokuu g1 = new Gokuu();
g1.hp = 100;
Karinsama k1 = new Karinsama();
k1.heal(g1); //Pass Goku and recover.
}
}
public class Karinsama {
public void heal(Gokuu g){
g.hp += 100;
System.out.println("I had Karin recover HP100 with senzu.")
}
}
** There is nothing in the field of the instance just created by new. ** ** However, strictly speaking, the initial value is set.
Initial value of field
Mold | value |
---|---|
int,short,long etc. | 0 |
char | ¥u000 |
boolean | false |
Array | null |
String,class | null |
The method that is automatically executed immediately after being new is called ** constructor **. Until now, Goku's HP was decided after the instance, If the basic 100 is fine, substitute 100 first in the Goku class.
public class Gokuu{
int hp;
public Gokuu(){
this.hp = 100;
}
}
There are two conditions that can be a constructor. (1) The method name is the same as the class. (2) The return value is not declared in the method (** void is also ✖ **)
Fields such as names that you want to change for each instance can be used as arguments.
public class SuperSaiyaJin {
int hp;
String name;
public SuperSaiyaJin(String name){
this.hp = 100;
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
SuperSaiyaJin gokuu = new SuperSaiyaJin ("Goku");
SuperSaiyaJin beji-ta = new SuperSaiyaJin ("Vegeta");
}
}
In fact, Java always has to define one constructor when instantiating. However, ** because the constructor is automatically generated if no one is defined ** Until now, it was possible to instantiate without worrying about it.
The constructor also determines by the argument and processes it.
public class SuperSaiyaJin {
//This works with no arguments
public SuperSaiyaJin(){
}
//This works with arguments
public SuperSaiyaJin(String name){
}
}
You can call your own constructor with this ();
.
public class SuperSaiyaJin {
int hp;
String name;
public SuperSaiyaJin(){
this("Goku");
}
public SuperSaiyaJin(String name){
this.hp = 100;
this.name = name;
}
}
In this state, even if you call SuperSaiyaJin () with no arguments
Since there is this (" Goku ");
, hp is set to 100.
Due to the independence of the instance, each new has its own field. (If you do new by yourself, it will not be referenced (shared)) However, if you use ** static **, it will be shared by all instances. This is convenient when you want to share some fields even if you create instances separately.
Fields with static are called ** static fields **.
Static fields can be used without instantiation.
Because of this feature, it is also called ** class variable **.
Usage: class name.static field name;
A method with static is called ** static method **. Also known as ** class method **. Together with static fields, they are called ** static members **.
Like static fields, static methods have the following three capabilities.
-(1) Since the method belongs (shared) to the class, it can be called with class name.method name ();
.
-② You can call it with instance variable name.method name ();
.
――③ You can call it without creating an instance.
Example.java
public class Item {
public static void main(String[] args) {
static int money;
static void setRandomMoney(){
Item.money = (int)(Math.random()*1000);
}
}
}
public class Main {
public static void main(String[] args) {
//Since it is static, new is unnecessary
Item.setRandomMoney();
System.out.println(Item.money); //※1
Item i = new Item();
System.out.println(i.money); //※2
}
}
"Math.random ()" generates random numbers less than 0.0 ~ 1.0 (double type) Until now, * 1 and * 2 have different numbers, but this time the variable money is static. In other words, since they are shared, the same value is output.
** You cannot call a field or method that does not have "static" in a static method. ** **
Methods with static can be called without instantiation, If there is a field declared without static in the block, an error will occur.
This is because fields without static cannot be called unless they are instantiated. ** Fields handled by static methods must be static fields. ** **
Click here for more ⇒ Part 2
Recommended Posts