Java programming: Polymorphism

Polymorphism is a method of providing various implementations with a single interface, and is a combination of programming methods such as inheritance and method override. For example, if you have an object variable of a superclass called “Shape”, you can create and assign a new type of class object underneath.

Shape A; //Declare an object variable A of a superclass type
A = new Oval(); //Create an object of the ellipse class in the object variable A of the superclass
A = new Rectangle(); //Create and assign a rectangular class object to the object variable A of the superclass
A.draw(); //Use the draw () method described in the rectangle class to draw a rectangle
flow of program logic

The draw () method declared in the Shape above creates a variety of models depending on the object of the subclass assigned. This is done by dynamically executing a mapping of the method draw () through a message.

Calling objects to work is called a message. It can be divided into the following three types.

  • The name of the object to receive the message (address)
  • the method name of the receiving object that the sending object wants to execute
  • Parameters to pass to the method you want to execute

Below is a basic object-oriented Java programming example that implements class generation and inheritance.

//Create class A
class A {
	private int result1;
	public int add(int x, int y) { //Create Method
		result1 = x + y;
		return result1;
	public int subtraction(int x, int y) {
		result1 = x - y;
		return result1;

//Inherits from class A and creates class B.
//Class B inherits from A and can use the A method.
class B extends A {
	private int result2;
	public int multi(int x, int y) {
		result2 = x * y;
		return result2;
	public int divide(int x, int y) {
		result2 = x / y;
		return result2;

class TestAB {
	public static void main(String args[]) {
		int temp;

		A object_a = new A();
		B object_b = new B();

		//Use the add() method of the generated object
		temp = object_a.add(10, 20);
		System.out.println('Add execution result of A'  + temp);

		//The object_b object does not have an add() method, but it inherits the superclass, so it can perform the add() method.
		temp = object_b.add(1, 2);
		System.out.println('Add execution result of B'  + temp);

		temp = object_b.multi(2, 2);
		System.out.println('Multi execution result of B'  + temp);

		//Error: object_a object does not have a multi() method
		temp = object_a.multi(20, 20);
		System.out.println('Multi execution result of A'  + temp);

Share This Post

댓글 남기기

이메일은 공개되지 않습니다. 필수 입력창은 * 로 표시되어 있습니다

Latest Post