Programming in Java on Your Computer
- Classes and Objects in BlueJ
- Trying out Code in BlueJ
- The Code for Creating and Using Objects
- Source Code and Methods
- Accessors and Mutators
- Constructor Code
- Class Code
- Simple Debugging
- Interactive Picture
- Refactoring Code with Inheritance
Refactoring Code with InheritanceOptional Node
Premium Content - Free Preview
If you examine the Circle, Triangle and Square Classes, you'll notice that there's a large amount of code overlap between them. This usually means that you should refactor your code to get rid of the duplication. In this case, you could use inheritance so that each shape can inherit from a superclass called
Shape. To see if Inheritance is a good idea, you can use the IS-A test:
- Square Is a Shape?
- Circle Is a Shape?
- Triangle Is a Shape?
Hopefully you answered yes to all of these questions. That means it would make sense to create a new superclass
Shape and make Square, Circle, and Triangle inherit from it.
- Create a new Class called Shape.
- Look at the Square Class and see which instance variables it has in common with the other shapes and which is uniquely Square's.
- Look at the Square Class and examine what methods it has in common with other shapes and what is uniquely Square.
- Cut and paste all of the non-unique methods and instance variables from Square to the new Shape class.
- Make Square inherit from Shape by using the
Then you need to adjust the code to get the new, lean Square class to work:
- variable access - The private variables in Shape will not be available to Shape's subclasses. Remove the private modifier from them.
- constructor - Most of the constructor can be moved to Shape also. However, you will need to set
sizein Square. You can call
superto explicitly set everything else.
abstract keyword and Polymorphism
What would an instance of the superclass Shape look like? It would be hard to draw a Shape without having a specific one in mind. This means that it would make sense to make the Shape class
abstract class is a class that cannot have instances of it created. It exists for its subclasses to inherit from and create their own instances. You can declare a class
abstract by adding the keyword before