Java method inheritance: overloading, overriding

Java uses overloading and overriding in method inheritance. Overloading and overriding are important concepts for implementing object-oriented language polymorphism. Sometimes two concepts are confused, but overloading and overriding are different concepts.

Overloading

Overloading is the act of using constructors or methods of the same name in the same class. When overloading, the number and type of parameters must be different.

Overriding

Overriding is the act of defining methods of the same name between classes that are inherited. Overriding has the advantage that you can create a new class by slightly changing the method implementation part of the existing class. When overriding, the number and type of parameters must be the same.

class A {
	int i;
	int j;

	void setij(int x, int y) {
		i = x;
		j = y;
	}
}

class B extends A {
	int total;

	void sum() {
		total = i + j;
	}
}

class Inheritance4 {
	public static void main(String args[]) {
		B subOb = new B();

		subOb.setij(10, 12); //Inherited from class A
		subOb.sum(); //Inherited from class B
		System.out.println('Sum of two numbers: ' + SubOb.tatal);
	}
}
Method inheritance example 1
class A {
	void show(String str) {
		System.out.println("Perform show(String str) on the superclass" + str) ;
	}
}

class B extends A {
	void show() {
		System.out.println("Perform show() method of subclass");
	}
}

class OverrideExam1 {
	public static void main(String args[]) {
		B over = new B();
		over.show("Java that is easy to understand");
		over.show();
	}
}
Method inheritance example 2
class A {
	void show() {
		System.out.println("Perform show(String str) on the superclass") ;
	}
}

class B extends A {
	void show() {
		System.out.println("Perform show() method of subclass");
	}
}

class OverrideExam2 {
	public static void main(String args[]) {
		B over = new B();
		over.show();
	}
}
Method inheritance example 3
class A {
	int i, j;

	A(int a, int b) {
		i = a;
		j = b;
	}

	void show() {
		System.out.println("Perform show(String str) on the superclass") ;
	}
}

class B extends A {
	int k;

	B(int a, int b, int c) {
		super(a, b); //Call the superclass's constructor
		k = c;
	}

	void show() {
		System.out.println("Perform show() method of subclass");
		System.out.println("=== Calling the superclass method with super ===");
		super.show();
	}
}

class OverrideExam3 {
	public static void main(String args[]) {
		B over1 = new B(10, 20, 30);
		System.out.println("i, j, k의 값 : " + over1.i = " " + over1.j + " ");
		over1.show();
	}
}
Method inheritance example 4

Share This Post

댓글 남기기

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

Latest Post