πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

πŸ–²

9.3 Overriding Methods

2 min readβ€’june 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Now that we know how to make subclasses and their constructors, it is time to write their methods. A subclass will inherit all public methods from the superclass. These methods will remain public in the subclass. Most methods that are inherited from the superclass do not need to be rewritten.
Any method that we call on an object must be defined within the class associated with that object or within the superclass.
However, some methods will have to be rewritten because their implementations will be different. This can be done by overloading, where the parameters for the methods are different but the methods achieve the same thing.

Overriding

The other way of doing this is overriding, which is when the method will have the same parameters, but their implementations will be different. Above the method header, we have to write @Override to show that this is an overridden method. For an overridden method, we usually don't have to write Javadoc comments since those should be inherited from the superclass.
A subclass can override methods inherited from its superclass. A subclass can also introduce new instance variables and methods that are not defined in the superclass.
In the Rectangle class, we will override the area method as follows:
/** Represents a rectangle */ public class Rectangle extends Quadrilateral { /** Makes a rectangle given a length and width */ public Rectangle(double length, double width) { super(length, width, length, width); } @Override public double Area() { //from the constructor, length is sideOne and width is sideTwo return sideOne * sideTwo; } }
Browse Study Guides By Unit
βž•Unit 1 – Primitive Types
πŸ“±Unit 2 – Using Objects
πŸ–₯Unit 3 – Boolean Expressions & if Statements
πŸ•ΉUnit 4 – Iteration
βš™οΈUnit 5 – Writing Classes
⌚️Unit 6 – Array
πŸ’ΎUnit 7 – ArrayList
πŸ’»Unit 8 – 2D Array
πŸ–²Unit 9 – Inheritance
πŸ–±Unit 10 – Recursion
🧐Exam Skills

Fiveable
Fiveable
Home
Stay Connected

Β© 2024 Fiveable Inc. All rights reserved.


Β© 2024 Fiveable Inc. All rights reserved.