In this lab, we are going to explore the concepts of inheritance, and how you could create a new class from an existing class, which will allow you to modify a certain class, and to change some behaviour in classes without fully understanding or reimplementing them.
You should know that every class in Java extends the Object
class, but what does this mean?
It means that Object
is our superclass, which our class (The subclass) will have all its functionality.
And we can expand this concept, so a superclass in a context could be the subclass in another context!
Notice that Rectangle
is the subclass for Shape
, but it's the superclass for Square
.
One of the most important things about inheritance is the ability to override methods, this will allow us to change the behaviour of certain methods in the superclass if we instantiated the subclass.
So in this example, we have the getArea
method, which will return zero if we created a shape, but if we created a rectangle it will return w*h
, notice that you won't find this very useful until you understand Polymorphism.
But here is another simple example, the method toString
is a method that converts an object to a string value, and you can find it in the Object
class, which by default will return the type and address of the instance, but we could modify it, so whenever we print a certain class it will return a useful data.
The main concept of Polymorphism is that you could store an instance of a subclass, in a superclass typed variable, which will allow us to do magical things!
Notice that s1
contains an instance of Square
, but its type is Shape
, but notice that you will be able to call only Shape
methods.
To check the type of the instance we could use instanceof
keyboard, for example:
And you can use casting to change if you want to consider s1 as Square
again, for example:
Return to Task 1 in Lab 1, and extend the Post
class to create a new class called SecretPost
, this post will have a password, so you couldn't see the content of it without entering the correct password.
Don't forget to allow the user to create secret posts!
Programming
Java
IUG