You are on page 1of 3

CMSC 22 LAB HANDOUT 08

OBJECTIVES

Attheendofthesession,thestudentsshouldbeableto:
Explaintheconceptofinheritance
Derivesubclassesoutofexistingclasses
Leveragetheadvantagesofinheritance
Useprotectedaccessmodifierinattributesandmethods
Overrideexistingmethodsfromthesuperclass

DISCUSSION

INHERITANCE
Inheritance isone of the core pillars ofobjectorientedprogramming. Itisamechanismthat allowsdevelopers toderive
newclasses(subclasses)outofexistingones(superclasses).

We can modela problem domainwithinheritance when there aredifferentkinds of objects thathave certain amount in
common with each other. Forexample,circles and rectangles sharethefeaturesof shapes. Theyallhave anorigin (x
and y) and anareaalbeitcomputations for the areasofcircles will be different from thatof the rectangles. Yeteachof
them also defines additional features that make them different from each other. Circles have radii and circumference
whilerectangleshavewidth,height,andperimeter.

Notallproblemdomains,however,shouldbemodeledusinginheritance.

THEEFFECTSOFINHERITANCE
The features of the superclass with access modifiers public and protected are passed down to its subclasses. These
featuresno longer haveto beexplicitlydeclaredintheclassspecificationofthesubclass. Becauseofthis,theamountof
workneededtocodethesubclassesarereduced.

INHERITANCEINJAVA
To derive a subclass from its superclass, the keyword
extends
is used. See the following example where the class
AdminisderivedfromtheclassUser.

public class User {


protected String username;
protected String password;
public void login() { }
}

public class Admin


extendsUser {
public void ban(User user) { }
}

Although not declared within its class specification, the classAdminhastheattributes username andpasswordandthe
methodlogin().ThesefeatureswereinheritedfromtheclassUser.

InJava,asubclasscanonlyhaveonesuperclass.

THEKEYWORD
super

Thekeyword
super
canbeusedwithinthesubclasstorefertoitssuperclass.Itcanbeusedintwoways:
invoketheconstructorofthesuperclass
invokethemethodofthesuperclass


public class User {
protected String username;
protected String password;
public User(String u, String p) {
this.username = u;
this.password = p;
}
public void login() { }
public void greet() {
System.out.println(Hi!);
}
}

public class Admin


extendsUser {
public Admin(String u, String p) {
super(u, p);

}
public void ban(User user) { }
public void acknowledge() {
super.greet();

System.out.println(Im an admin);
}
}

METHODOVERRIDING
If the implementation of a methodinheritedfromthesuperclassdoes not suit the subclass,thesubclasscanchooseto
overrideitbyredeclaringthemethodinitsclassspecification.

public class User {


protected String username;
protected String password;
public User(String u, String p) {
this.username = u;
this.password = p;
}
public void login() { }
public void greet() {
System.out.println(Hi!);
}
}

public class Admin


extendsUser {
public Admin(String u, String p) {
super(u, p);
}
public void ban(User user) { }
public void acknowledge() {
super.greet();
System.out.println(Im an admin);
}
public void greet() {

System.out.println(Hello!);
}
}

ABSTRACTCLASSESANDABSTRACTMETHODS
We declare a classasabstractif we want toleavethe implementationof its abstractmethodstoitssubclasses.Abstract
classes are designed tobecomesuperclasses. Abstract methods do not havean implementation body just a method
signature.

public abstract class User {


protected String username;
protected String password;
public User(String u, String p) {
this.username = u;
this.password = p;
}
public abstract void login();

public void greet() {


System.out.println(Hi!);
}
}

public class Admin


extendsUser {
public Admin(String u, String p) {
super(u, p);
}
public void ban(User user) { }
public void acknowledge() {
super.greet();
System.out.println(Im an admin);
}
public void greet() {
System.out.println(Hello!);
}
public void login() {
/* implementation */
}
}

EXERCISE

1.

Doesthe
Rectangle
classhave
x
andy
attributes?Explainyouranswer.

2.

Implementtheconstructor
Rectangle(int,int,double,double)
theconstructorshouldinitializetheorigin
ofthe
Rectangle
instancealongwithits
width
and
height
.

3.

Implementthemethod
getPerimeter()
itshouldreturntheperimeterofthe
Rectangle
instance

4.

Implementthemethod
getArea()
itshouldreturntheareaofthe
Rectangle
instance

5.

Overridethemethod
getString()
it should return the
String
representation of the
Rectangle
instance.An
exampleisgivenbelow:
{

x: 20,
y: 20,
radius: 100.0,
circumference: 628.32,
area: 31415.93
}

6.

Makethe
Circle
classasubclassof
Rectangle
class

7.

Implement the constructor


Circle(int, int, double)
the constructor should initialize the origin of the
Circle
instancealongwithits
radius
.

8.

Implementthemethod
getCircumference()
itshouldreturnthecircumferenceofthe
Circle
instance

9.

Implementthemethod
getArea()
itshouldreturntheareaofthe
Circle
instance

10. Override the method


getString()
it should return the
String
representation of the
Circle
instance. An
exampleisgivenbelow:
{
x: 20,
y: 240,
width: 100.0,
height: 60.0,
perimeter: 320.0,
area: 6000.0
}

Foritems1114,assumethattheaccessmodifiersofx

andy

oftheclass
Shape
werechangedtop
rotected
.

11. Implementtheconstructor
Rectangle(int, int, double, double)
withoutusingthekeyword
super
.
12. Implementtheconstructor
Circle(int, int, double)
withoutusingthekeyword
super
.
13. Is itpossible to access theattributes
x and
y ofboth
Circle
and
Rectangle
instanceswithintheclassMain?
Explainyouranswer.

14. Explainwhythere isno longer a need forCircleand Rectangle classes toimplement


getX()and
getY()while
thereisaneedtoimplement
toString()
?
15. Showtoyourlaboratoryinstructorthattheclass
Main
candraw
Circle
and
Rectangle
instances.

You might also like