Thu Sep 16 2021

Method Overriding

File Name: method-overriding.java

/* Power calculation */
import java.io.*;

class square {

	/* Global variables */
	int number, answer;

	square(int no) {
		number = no;
		answer = number * number;
	}

	void calculate() {
		System.out.println("Square: "+answer);
	}
}

/* Extend parent class into child class */
class cube extends square {
	int answer1;

	cube(int no) {
		super(no);
		answer1 = answer * number;
	}

	void calculate() {
		System.out.println("Cube: "+answer1);
	}
}

class method_overriding {
	public static void main(String args[ ]) {
		square sq = new square(5);
		sq.calculate();
		cube cb = new cube(5);
		cb.calculate();
	}
}




/* Output */
Square: 25
Cube: 125

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.