[Easy-to-understand explanation! ] How to use Java polymorphism

1. Prior knowledge

-[Latest] How to build Java environment on Ubuntu

-[Even beginners can do it! ] How to create a Java environment on Windows 10 (JDK14.0.1)

-[Easy-to-understand explanation! ] How to use Java instance

-[Even beginners can do it! ] How to install Eclipse on Windows 10 (Java environment construction)

-[Easy-to-understand explanation! ] How to use Java encapsulation

-[Easy-to-understand explanation! ] How to use Java inheritance [Override explanation]

-[Easy-to-understand explanation! ] Type conversion of reference type in Java

As prior knowledge, the contents of the above link are required.

2. What is polymorphism?

--Polymorphism means that objects with different processing can be handled by the same operation. --The operating side can use the operation without being aware of the difference in the processing of the object. --Polymorphism is also called diversitypolymorphism polymorphism. --Polymorphism is realized by treating an instance of a subclass that inherits the abstract class with the abstract class type.

3. What is an abstract class?

--A abstract class is a class created on the assumption that it will be inherited. --The abstract class has afeature that cannot be instantiated. --In theabstract class, you can define a" abstract method" that is supposed to be overridden. --Define abstract class and abstract method with "ʻabstract modifier". --The abstract method cannot have the private / static / final qualifier. --When using the abstract class, define a subclass that inherits the abstract class andoverride theabstract method. --A class that inherits the abstract class is called a concrete class`.

4. Basic way of writing polymorphism

Test class


package package name;
public class main class name{
    public static void main(String[] args) {
        //Instance generation
Subclass name variable name=new subclass name();
        //Execution of processing
Variable name.Abstract method name(Actual argument)
    }
}

Abstract class


package package name;
abstract class abstract class name{
    //Definition of instance variables
private type name variable name;

    //Constructor (executed when instantiating)
Abstract class name(Type name argument){
Initialization process, etc.
    }
    //Abstract method
abstract abstract method name(Type name argument);
}

Subclass


package package name;
class subclass name extends abstract class name{
    //Definition of instance variables
private type name variable name;

    //Constructor (executed when instantiating)
Subclass name(Type name argument){
        super(argument);
Initialization process, etc.
    }
    //override(Abstract method)
    @Override
Abstract method name(Type name argument){
        //processing
    }
}

--Basic polymorphism is written as above.

5. Preparation

01.png

  1. Start Eclipse and select [File (F)]-> [New (N)]-> [Java Project]. 02.png
  2. Enter Test1 for the project name and click the Done button. 03.png
  3. Select [File (F)] → [New (N)] → [Class]. 05.png
  4. Enter Test1 for the package and name and click the Done button. 06.png
  5. Confirm that Test1.java has been created. 01.png Enter Test1 in the package and Greeting in the name, check ʻabstract, and click the Finishbutton in the same procedure as in 6.3. ![02.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/449867/1ad39e0b-5d11-d4dc-9bb6-f641b6fd3763.png) EnterTest1 in the package, GoodMorningin the name, andTest1.Greeting in the superclass, as in 8.3, and click the Finishbutton. ![03.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/449867/9a281438-d32b-e696-feef-005528b0db34.png) EnterTest1 in the package, Helloin the name, andTest1.Greeting in the superclass, as in 9.3, and click the Finishbutton. ![04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/449867/e336150c-0447-e10d-61e2-df7ef1362729.png) EnterTest1 in the package, GoodEveningin the name, andTest1.Greeting in the superclass, as in 10.3, and click the Finish` button. 05.png
  6. Success if Test1.java, Greeting.java, GoodMorning.java, Hello.java, and GoodEvening.java are created.

6. Description example

Test1.java


package Test1;
public class Test1 {
    public static void main(String[] args) {
        //Instance generation
    	Greeting[] greeting = {new GoodMorning("A"),new GoodMorning("B"),new GoodMorning("C")};

    	//Greeting display
    	for(int i = 0;i < greeting.length;i++) {
    		greeting[i].showGreeting();
    	}
    }
}

Greeting.java


package Test1;
public abstract class Greeting {
	//Instance variables
	private String name;

	//constructor
	public Greeting(String name) {
		this.name = name;
	}
	// getter
	public String getName() {
		return name;
	}
	//Display greetings
	abstract void showGreeting();
}

Greeting.java


package Test1;
public class GoodMorning extends Greeting {
	//constructor
	public GoodMorning(String name) {
		super(name);
	}
	//Display greetings
	@Override
	void showGreeting() {
		System.out.println(getName()+"Good morning, Mr.");
	}
}

--Copy the above sentence, specify S-JIS as the character code, save the file name as Test1.java, Greeting.java, GoodMorning.java, and execute it. .. ↓ ↓ 07.png

7. Reasons for polymorphism

--Object-oriented treats any event as a object. --Therefore, the number of classes to be instantiated increases in proportion to thenumber of objects``. ――If you think ofwriting code for the number of objects, it becomes a tremendous number and it is difficult to write it down. --Polymorphism finds commonalities between objects and abstracts them to simplify the code and `reduce the amount of code written``.

A system in which A, B, and C greet each other

--A, B, C greet in order.

Test1.java


package Test1;
public class Test1 {
    public static void main(String[] args) {
        //Instance generation
    	GoodMorning[] goodmorning = {new GoodMorning("A"),new GoodMorning("B"),new GoodMorning("C")};
    	Hello[] hello = {new Hello("A"),new Hello("B"),new Hello("C")};
    	GoodEvening[] goodevening = {new GoodEvening("A"),new GoodEvening("B"),new GoodEvening("C")};

    	//Greeting display
    	for(int i = 0;i < goodmorning.length;i++) {
    		goodmorning[i].showGreeting();
    	}
    	for(int i = 0;i < hello.length;i++) {
    		hello[i].showGreeting();
    	}
    	for(int i = 0;i < goodevening.length;i++) {
    		goodevening[i].showGreeting();
    	}
    }
}

Hello.java


package Test1;
public class Hello {
	//Instance variables
	String name;

	//constructor
	public Hello(String name) {
		this.name = name;
	}
	//Display greetings
	void showGreeting() {
		System.out.println(name+"Hey,.");
	}
}

GoodMorning.java


package Test1;
public class GoodMorning{
	//Instance variables
	String name;

	//constructor
	public GoodMorning(String name) {
		this.name = name;
	}
	//Display greetings
	void showGreeting() {
		System.out.println(name+"Good morning, Mr.");
	}
}

GoodEvening.java


package Test1;
public class GoodEvening {
	//Instance variables
	String name;

	//constructor
	public GoodEvening(String name) {
		this.name = name;
	}
	//Display greetings
	void showGreeting() {
		System.out.println(name+"Good evening, Mr.");
	}
}

--Copy the above sentence, specify S-JIS as the character code, and save the file name as Test1.java, GoodMorning.java, Hello.java, GoodEvening.java. , When executed, it becomes like this. ↓ ↓ 06.png

--In the above example, polymorphism is not used, so there arethreearrays, and there is a corresponding for statement. --You can combine arrays into one by abstracting using polymorphism. --The following is the abstraction of GoodMorning.java, Hello.java, and GoodEvening.java` in the above example.

Test1.java


package Test1;
public class Test1 {
    public static void main(String[] args) {
        //Instance generation
    	Greeting[] greeting = {
    			new GoodMorning("A"),new GoodMorning("B"),new GoodMorning("C"),
    			new Hello("A"),new Hello("B"),new Hello("C"),
    			new GoodEvening("A"),new GoodEvening("B"),new GoodEvening("C")
    			};

    	//Greeting display
    	for(int i = 0;i < greeting.length;i++) {
    		greeting[i].showGreeting();
    	}
    }
}

Greeting.java


package Test1;
public abstract class Greeting {
	//Instance variables
	private String name;

	//constructor
	public Greeting(String name) {
		this.name = name;
	}
	// getter
	public String getName() {
		return name;
	}
	//Display greetings
	abstract void showGreeting();
}

Hello.java


package Test1;
public class Hello extends Greeting{
	//constructor
	public Hello(String name) {
		super(name);
	}
	//Display greetings
	@Override
	void showGreeting() {
		System.out.println(getName()+"Hey,.");
	}
}

GoodMorning.java


package Test1;
public class GoodMorning extends Greeting {
	//constructor
	public GoodMorning(String name) {
		super(name);
	}
	//Display greetings
	@Override
	void showGreeting() {
		System.out.println(getName()+"Good morning, Mr.");
	}
}

GoodEvening.java


package Test1;
public class GoodEvening extends Greeting {
	//constructor
	public GoodEvening(String name) {
		super(name);
	}
	//Display greetings
	@Override
	void showGreeting() {
		System.out.println(getName()+"Good evening, Mr.");
	}
}

--Copy the above sentence, specify S-JIS as the character code, and name the file``Test1.java, Greeting.java, GoodMorning.java, Hello.java, GoodEvening. If you save it as .java` and run it, it will look like this. ↓ ↓ 06.png

7. Related

-[Useful to remember !!!] Easy creation of constructor and getter / setter in Eclipse -[Useful to remember !!!] Easy creation of inherited class in Eclipse -[Even beginners can do it! ] How to write Javadoc -[Easy-to-understand explanation! ] How to use Java overload

Recommended Posts

[Easy-to-understand explanation! ] How to use Java polymorphism
[Easy-to-understand explanation! ] How to use Java instance
[Easy-to-understand explanation! ] How to use ArrayList [Java]
[Easy-to-understand explanation! ] How to use Java overload
[Easy-to-understand explanation! ] How to use Java encapsulation
[Easy-to-understand explanation! ] How to use Java inheritance [Override explanation]
[Java] How to use Map
How to use java Optional
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to use string.format
How to use Java Map
How to use Java variables
[Java] How to use Optional ①
How to use Java HttpClient (Get)
How to use Java HttpClient (Post)
[Java] How to use join method
[Java] How to use LinkedHashMap class
[JavaFX] [Java8] How to use GridPane
How to use class methods [Java]
[Java] How to use List [ArrayList]
How to use classes in Java?
[Processing × Java] How to use arrays
How to use Java lambda expressions
[Java] How to use Math class
How to use Java enum type
Multilingual Locale in Java How to use Locale
[Java] How to use the File class
[Java] How to use the hasNext function
How to use submit method (Java Silver)
[Java] How to use the toString () method
[Processing × Java] How to use the loop
How to use Java classes, definitions, import
[Java] [Maven3] Summary of how to use Maven3
[Processing × Java] How to use the class
How to use Java Scanner class (Note)
[Processing × Java] How to use the function
[Java] How to use the Calendar class
[Java] Learn how to use Optional correctly
try-catch-finally exception handling How to use java
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use Twitter4J
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use hashes
How to use JUnit 5
How to use Dozer.mapper
How to use Gradle
How to use org.immutables