Click here to Skip to main content
15,902,842 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,

I have created below shown classes in java but my method overriding is not working:

Java
package day3.inheritance;

//base class or parent class or super class
public class Box {
	public void calculateArea(int length, int width) {
		System.out.println("Area is: " + (length*width));
	}
}


============================================

package day3.inheritance;

//Inheritance: when a class acquires properties of another class
//subclass
public class NewBox extends Box {
	public void calculateVolume(int length, int width, int height) {
		System.out.println("Volume= " + (length*width*height));
	}
	
	public void calulateArea(int length, int width) {
		System.out.println("Sub area = " + (length / width));
	}
}

==================================================================

package day3.inheritance;

public class TestBox {
	public static void main(String[] args) {
		Box FedEx = new Box();
		FedEx.calculateArea(3, 4);
		
		NewBox ups = new NewBox();
		ups.calculateVolume(4, 5, 6);
		ups.calculateArea(4, 2);
	}

}


What I have tried:

Output is coming as below:

12
120
8

it should be
12
120
2

I was practicing from a video tutorial he wrote the same code. His code worked but not mine, Please help.
Posted
Updated 30-Jul-18 22:40pm
v2
Comments
Member 13931913 31-Jul-18 2:07am    
No Thaddeus. My intent is to override the method of parent class in the subclass NewBox. The output should be subarea = 4/2=2

Java
public void calulateArea(int length, int width) {

You spelled the method name wrong (missing 'c'). It should be calculateArea.
 
Share this answer
 
System.out.println("Sub area = " + (length / width));

In NewBox, You define the area as length/width, but it should be length*width.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900