June 2: OOP: Inheritance and Graphics

Download Report

Transcript June 2: OOP: Inheritance and Graphics

Relationships Between Classes
• The most common types of relationships:
– Dependency
• A class depends on another class if it uses objects of that class.
The “knows about” relationship.
– Aggregation
• A class aggregates another if its objects contain objects of the
other class. The “Has-a” relationship.
– Inheritance
• Inheritance is a relationship between a more general class (the
superclass) and a more specialized class (the subclass). The
“is-a” relationship.
Inheritance
• Motivation
– Code reuse
– Conceptual modeling
How to do inheritance in Java
• Syntax
class A extends B{
…
}
• Class A automatically inherits all members (methods and
attributes) of class B
– Only need to specify new methods and attributes in the subclass!
– Constructor is not inherited
public class Account {
protected double balance;
public Account( double amount ) {
balance = amount;
}
public Account() { balance = 0.0; }
public void deposit( double amount ) { balance += amount; }
public double withdraw( double amount ) {
if (balance >= amount) {
balance -= amount;
return amount; }
else
return 0.0;
}
public double getbalance() { return balance; }
}
public class InterestBearingAccount extends Account {
private static double default_interest = 7.95;
private double interest_rate;
public InterestBearingAccount( double amount, double interest) {
balance = amount;
interest_rate = interest;
}
public InterestBearingAccount( double amount ) {
balance = amount;
interest_rate = default_interest;
}
public void add_monthly_interest() {
// Add interest to our account
balance = balance + (balance * interest_rate / 100) / 12;
}
}
Superclass and Subclass
• general vs. specialized
• subclass is also called derived class, extended class, or
child class
• superclass is also called base class or parent class
Inheritance class architecture
Student
Undergrad
Account
Postgrad
Master’s
Checking
Account
PhD
Savings
Account
“Is a” Relationship
• An Undergrad “is a” Student
• But not all inheritances are intended for “is a” type
of relationship
– Some are simply expanding information
• Point (x, y)  Circle (x, y, r)  Cylinder (x, y, r, h)
Java Class Hierarchy
• Every class is a subclass of Object!
– Implicitly extends the Object class
A class has exactly one direct superclass (except for
the Object class)
What You Can Do in a Subclass
• All attributes are inherited from the superclass.
• You can declare an attribute in the subclass with the same
name as the one in the superclass, thus hiding/shadowing it
(not recommended).
• You can declare new attributes in the subclass that are not
in the superclass.
• The inherited methods can be used directly as they are.
• You can write a new instance method in the subclass that
has the same signature (name, plus the number and the
type of its parameters) as the one in the superclass, thus
overriding it.
• You can declare new methods in the subclass that are not
in the superclass.
• You can write a subclass constructor that invokes the
constructor of the superclass, either implicitly or by using
the keyword super.
Inheritance and Attributes
• Private attributes
– inherited, but not directly accessible
– only accessible through public methods of the superclass
• Redefining an attribute in the subclass
– The attribute inherited from the superclass is not replaced!
• Stored in different memory areas
– the subclass attribute will hide/shadow the one defined in the
superclass
Avoid Shadowing Instance Attributes
public class CheckingAccount extends BankAccount {
…
public void deposit(double amount) {
transactionCount++;
balance = balance + amount; // ERROR!!
}
}
How about adding an instance attribute balance to the subclass?
public class CheckingAccount extends BankAccount {
…
// Shadowing the superclass attribute : don’t
private double balance;
public void deposit(double amount) {
transactionCount++;
balance = balance + amount;
}
}
Example
public class Parent{
...
private int att;
public void setAtt(int n){
att = n;
}
}
public class Offspring extends Parent{
private int att;
public void meth(){
att = 4;
//
sets Offspring’s att
setAtt(3);// sets Parent’s att
}
}
// in main
Offspring o = new Offspring();
o.meth();
Methods: Overriding vs. Overloading
• Overriding
– A method in the subclass which has the same signature and
return type as a method in the superclass
– The method in the subclass overrides the method inherited
from the superclass
– The method from superclass is still available through
super
• Overloading
– Several methods with the same name in the same class
– Only possible when the signatures of methods are different
– Signature
• the combination of the method's name along with the number
and types of the parameters (and their order).
Example
public class Parent {
public void meth() // #1
{ ...
}
public void meth(int n) // #2
Overloading
{ ...
}
...
}
public class Offspring extends Parent {
Overriding #2
public void meth(int n) // #3
{ ...
}
...
}
...
// in main
Parent o1 = new Parent();
Offspring o2 = new Offspring();
calls #1
o1.meth();
calls #2
o1.meth(31);
calls #1
o2.meth();
calls #3
o2.meth(29);
Accessing Superclass Members
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
public class Subclass extends Superclass {
public void printMethod() {
//overrides printMethod in Superclass
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Output:
Printed in Superclass.
Printed in Subclass
Failing to Invoke the Superclass Method
public class Subclass extends Superclass {
…
public void printMethod() {
printMethod(); // should be super.printMethod() !!
System.out.println("Printed in Subclass");
}
}
Calling printMethod() == calling this.printMethod()
public void withdraw(double amount){
transactionCount++;
withdraw(amount); // should be super.widthdraw(amount)!
}
Don’t forget to call the superclass method when necessary
protected Members
• protected access members
– Between public and private in protection
– Accessed only by
• Superclass methods
• Subclass methods
• Methods of classes in same package
– package access
– allows the derived classes to directly access those protected
attributes (no need to use methods to access them)
– if the superclass’s attribute is protected, and there is another
derived class attribute with the same name (bad idea !), you
can refer to the base class attribute as super.attribute.
Constructors and Inheritance
public class BankAccount {
private double balance;
public BankAccount(){ balance = 0; }
public BankAccount(double initialBalance){
balance = initialBalance;
}
…
}
public class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(){
interestRate = 0;
balance = 0; Wrong! The subclass doesn’t have access to this attribute
}
}
Constructors and Inheritance
• the correct solution:
public class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(){
interestRate = 0;
}
the default constructor from the
superclass with 0 parameters will
be called automatically.
}
equivalent
public class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(){
super();
Explicitly calling the constructor of the superclass
interestRate = 0;
}
}
Q: What if all constructors in the superclass require
parameters??
A: Compilation error
Constructors and Inheritance
public class SavingsAccount extends BankAccount{
private double interestRate;
//a constructor with two parameters
public SavingsAccount(double initialBalance, double rate){
// call the 1 param constructor of the superclass explicitly
super(initialBalance);
interestRate = rate;
}
…
}
1. class Student {
2.
// instance attributes
3.
private String name;
4.
private long number;
5.
6.
//constructor
public Student(String aName, long
aNumber){
7.
name = aName;
8.
number = aNumber;
9.
}
10.
// instance methods
11.
public void setName(String aName){
12.
name = aName;
13.
}
14.
public String getName(){
15.
return name;
16.
}
17.
public void setNumber(long aNumber){
18.
number = aNumber;
19.
}
20.
public long getNumber(){
21.
return number;
22.
}
23.
public String toString(){
24.
return "Student[name=" + name +
",number=" + number + "]";
25.
}
26.}
1. class Undergrad extends Student{
2.
// instance attributes
3.
private String major;
4.
private int year;
5.
6.
//constructor
public Undergrad(String aName, long
aNumber, String aMajor, int aYear){
7.
super (aName, aNumber);
8.
setMajor (aMajor);
9.
setYear(aYear);
10.
}
11.
// new methods
12.
public void setMajor(String aMajor){
13.
major = aMajor;
14.
}
15.
public String getMajor(){
16.
return major;
17.
}
18.
public void setYear(int aYear){
19.
year = aYear;
20.
}
21.
public int getYear(){
22.
return year;
23.
}
24.
// overriding the base class toString()
25.
public String toString(){
26.
return "Undergrad[name=" + getName() +
27.
",number=" + getNumber() + "
28.
,major=" + major +
29.
",year=" + year + "]";
30.
}
31.}
Overriding
public class Inh1 {
public static void main(String[] args){
Student s1 = new Student("John",202123456);
System.out.println("s1 is " + s1.getName());
System.out.println(s1.toString());
Undergrad s2 = new Undergrad("Mary",201234567,"ITEC",1);
System.out.println("s2 is "+s2.getName());
//inherited
s2.setName("Mary Ellen");
//inherited
System.out.println("s2 is in year " + s2.getYear());
//new method
System.out.println(s2.toString());
}
}
Output:
s1 is John
Student[name=John,number=202123456]
s2 is Mary
s2 is in year 1
Undergrad[name=Mary Ellen,number=201234567,major=ITEC,year=1]
Note
• Another implementation of the subclass method
toString(), which uses the superclass toString():
public String toString(){
// call superclass’s method
String s = super.toString();
// make appropriate changes & return
s = s.substring(s.indexOf("["),s.length()-1);
return "Undergrad" + s + ",major=" + major + ",year=" + year
+ "]";
}
The super Keyword
• super(…): calls the constructor of the superclass
(0 or more parameters)
• super.aMethod(…): calls the method
aMethod(…) from the superclass
• When used in a superclass constructor, super(…)
must be the first statement of the constructor.
• super.aMethod(…) can be anywhere in any
subclass method
To summarize…
• The constructor(s) of the superclass can be called
explicitly in the subclass constructor using
super(…) (with 0 or more parameters)
• If superclass’s constructor is not called explicitly,
super() will be called by default at the
beginning of the subclass constructor.
public class Student{
public Student() {
Example
name = "UNKNOWN";
number = -1;
}
public Student(String aName, long aNumber){
name = aName;
number = aNumber;
} ...
private String name;
private long number;
}
public class Undergrad extends Student{
public Undergrad(){
super(); // calls Student’s 0 args constructor
major = "general";
year = 1;
}
public Undergrad(String aName, long aNumber, String aMajor, int aYear){
super(aName, aNumber); // calls Student’s 2 args constructor
major = aMajor;
year = aYear;
} ...
private String major;
private int year;
}
// in main
Undergrad u = new Undergrad("John", 201234567, "ITEC", 1);
Multiple Layers of Inheritance
• Each ancestor’s constructor is called in turn
public class PartTimeUndergrad extends Undergrad{
public PartTimeUndergrad(){
super();
// calls Undergrad’s 0 args constructor
courseLoad = 2.5;
}
public PartTimeUndergrad(String aName, long aNumber, String
aMajor, int aYear, double aLoad){
// calls Undergrad’s 4 args constructor
super(aName, aNumber, aMajor, aYear);
courseLoad = aLoad;
}
...
private double courseLoad;
}
Converting Between Subclass and
Superclass Types
• Converting a subclass type to a superclass type
SavingsAccount savings = new SavingsAccount(5);
BankAccount anAccount = savings;
Object anObject = savings;
(All references can be converted to the type Object)
– savings, anAccount, and anObject all refer to the same
object of type SavingsAccount
– anAccount knows less about the SavingsAccount object
• E.g., only methods defined in BankAccount are accessible
– anObject knows even less
Converting subclass type reference to
superclass type reference
• Difference between converting references and
numerical conversion
– Numerical: different representations, copies are made
• E.g., int i = 1; double d = i;
– References: the value of the reference stays the same: the
memory address of the object. No copies of objects are made!
• Useful for code reuse
public void transfer(double amount, BankAccount other) {
withdraw(amount);
other.deposit(amount);
}
can pass to it any
argument of type
BankAccount or its
subclasses
Converting superclass type reference to
subclass type reference
• Casting
SavingsAccount savings = (SavingsAccount) anAccount;
This can be dangerous: anAccount is not necessarily a
reference to a SavingsAccount object!
• Use instanceof to protect against bad casts
if (anAccount instanceof SavingsAccount) {
SavingsAccount savings = (SavingsAccount) anAccount;
}
Inheritance Example
• Define a method
public double calculateFees(double courseload)
for Student and Undergrad which returns the fees to be
paid by the student depending on his/her course load.
Suppose that for students generally, the fees are
$800/course, and that for undergraduates, there is an
additional incidental charge of $100 for first year students
and $150 for students in later years.
public class Student{
...
public double calculateFees(double courseload){
final double FEE_PER_COURSE = 800;
return FEE_PER_COURSE * courseload;
}
...
}
public class Undergrad extends Student{
...
// override Student’s calculateFees method
public double calculateFees(double courseload){
final double INCIDENTAL_FEE_Y1 = 100;
final double INCIDENTAL_FEE_Y_GT_1 = 150;
double fee = super.calculateFees(courseload);
if (year == 1)
fee = fee + INCIDENTAL_FEE_Y1;
else
fee = fee + INCIDENTAL_FEE_Y_GT_1;
return fee;
}
...
}
// in main
Student s = new Student("Mary", 202345678);
System.out.println(s + " fees: " + s.calculateFees(4.5));
Undergrad u = new Undergrad("John", 201234567, "ITEC", 1);
System.out.println(u + " fees: " + u.calculateFees(4.5));
// The following will not COPY an object; it will just create
// another reference to the same object
Student s1=u;
// s1 will only see the student part of u
The Cosmic Superclass
• Every class in Java inherits from the Object class
• Methods in the Object class
– String toString(): returns a string representation of
the object
– boolean equals(Object anotherObject): tests
whether the object equals another object
– Object clone(): makes a full copy of an object
• You can use the Object methods or, better,
override them in your classes
s1=s.clone();
if (s1.equals(s))
System.out.println(“The two objects are identical”);
Example: Overriding the equals method
• Use the equals method to compare two objects
by their contents
– if (coin1.equals(coin2)) …
// if the contents are the same
– Different from if (coin1 == coin2), which tests whether the two references
are to the same object.
• Implementing the equals method
public class Coin {
. . .
value
public boolean equals(Object otherObject) {
name
Coin other = (Coin) otherObject;
return name.equals(other.getName())
&& value.equals(other.getValue());
}
. . .
}
Coin
Applet (JApplet)
• Applets are Java programs embedded in Web pages
• Class Applet or JApplet has the methods init(), start(),
stop() which will be called automatically.
– When you inherit JApplet you can overwrite these methods for
specific scenarios.
import java.applet.Applet;
import java.awt.*;
public class RectangleApplet extends Applet {
public void paint(Graphics g) {
g.drawRect(5,10,20,30);
}
}
final Methods and Classes
• In writing classes one has to keep in mind that future applications
might be extending them through inheritance.
• Design decisions:
– The class: Do you want others to define subclasses of this class?
– Attributes(fields): protected or private?
– Methods: Do you want the derived classes to override them?
• The final keyword
– preventing others from extending this class or from overriding certain
methods
– public final class String { . . .}: nobody can extend the String class
– final methods:
public class SecureAccount extends BankAccount{
public final boolean checkPassword(String password){
. . .
} // nobody can override this method
}
Abstract Classes
• Abstract classes
– Too generic to define real objects, no good default methods
• TwoDimensionalShape
• public void computeArea()
– Forcing the programmers of subclasses to implement this
method
• public abstract void computeArea();
– Objects of abstract classes cannot be instantiated
– Provides superclass from which other classes may inherit
• Normally referred to as abstract superclasses
• Concrete classes
– Classes from which objects are instantiated
– Provide specifics for instantiating objects
• Square, Circle and Triangle
Abstract Classes
• A class that defines an abstract method, or that
inherits an abstract method without overriding it,
must be declared as abstract.
• Can also declare classes with no abstract methods
as abstract
– preventing users from creating instances of that class
• Why abstract classes?
– Forcing programmers to create subclasses
– Avoiding useless default methods in superclasses others may
inherit by accident.
Introduction to Graphics
• An appealing feature of Java
• Made easy by many standard library calls that are
not included in many languages
• With graphics one can easily draw shapes, one can
control colors and fonts, one can organize the
screen in a user-friendly way.
Graphics
• An JOptionPane example
import javax.swing.JOptionPane;
public class DialogDemo {
public static void main(String[] args) {
String ans;
ans = JOptionPane.showInputDialog(null,
"Speed in miles per hour?");
double mph = Double.parseDouble(ans);
double kph = 1.621 * mph;
JOptionPane.showMessageDialog(null, "KPH = " + kph);
System.exit(0);
}
}
Frame Windows
import javax.swing.*;
public class EmptyFrameViewer{
public static void main(String[] args) {
JFrame frame = new JFrame();
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("An Empty Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
awt and swing
• Most of the GUI classes are provided in Java by
the Abstract Windowing Tools (AWT) package
(java.awt).
• AWT was expanded with the Swing classes
(javax.swing) in Java 2 platform
– Swing classes provide alternative components that have
more functionality than AWT
– We shall prefer using swing
• Part of the java class hierarchy structure
– Classes of AWT such Color, Font, Graphics,
Component are derived from the Object superclass.
Java’s Coordinate System
• Scheme for identifying all points on screen
• Upper-left corner has coordinates (0,0)
• Coordinate point composed of x-coordinate and ycoordinate
Java coordinate system. Units are
measured in pixels.
+
(0, 0)
x
xy
( , )
y
+
Y a xis
X a xis
Graphics Context and Graphics Objects
• Graphics context
– Enables drawing on screen
– Graphics object manages graphics context
• Controls how information is drawn
– Class Graphics is abstract
• Cannot be instantiated
• Contributes to Java’s portability
– Class Component method paint takes Graphics object
public void paint( Graphics g )
Color Control
• Class Color
– Defines methods and constants for manipulating colors
– Colors are created from red, green and blue components
• RGB values
Color class static constants and RGB
values.
Color Consta nt
Color
RGB value
public final static Color orange
orange
255, 200, 0
public final static Color pink
pink
255, 175, 175
public final static Color cyan
cyan
0, 255, 255
public final static Color magenta
magenta
255, 0, 255
public final static Color yellow
yellow
255, 255, 0
public final static Color black
black
0, 0, 0
public final static Color white
white
255, 255, 255
public final static Color gray
gray
128, 128, 128
public final static Color lightGray
light gray
192, 192, 192
public final static Color darkGray
dark gray
64, 64, 64
public final static Color red
red
255, 0, 0
public final static Color green
green
0, 255, 0
public final static Color blue
blue
0, 0, 255
Fig. 11.3 Color c la ss static c onsta nts a nd RGB va lues
Color methods and color-related Graphics
methods.
Method
Description
public Color( int r, int g, Creates a color based on red, green and blue contents expressed
int b )
as integers from 0 to 255.
public Color( float r, float Creates a color based on red, green and blue contents expressed
g, float b )
as floating-point values from 0.0 to 1.0.
public int getRed()
Color class
// Returns a value between 0 and 255 representing the red content.
public int getGreen()
Color class
// Returns a value between 0 and 255 representing the green
public int getBlue()
Color class
// Returns a value between 0 and 255 representing the blue
public Color getColor()
// Graphics class
content.
content.
Returns a Color object representing the current color for the
graphics context.
public void setColor( Color Sets the current color for drawing with the graphics context.
c ) // Graphics class
Color methods and color-related Graphics methods.
The Component Class
• A superclass for many classes in AWT
• Its method paint() takes a Graphics object as
an argument:
public void paint (Graphics g)
• Derived classes from Component will override
paint() to perform various graphics operations
with the help of the g Graphics object passed as
a parameter.
import java.awt.*;
import java.awt.event.*;
// Java extension packages
import javax.swing.*;
public class ShowColors extends JFrame {
// constructor sets window's title bar string and dimensions
public ShowColors()
{
super( "Using colors" ); // this will put a title on the frame bar
setSize( 400, 130 );
// size in pixels
show();
}
// draw rectangles and Strings in different colors
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
// setColor, fillRect, drawstring, getColor, getRed etc
// are methods of Graphics
// set new drawing color using integers for R/G/B
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
// set new drawing color using floats
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );
// set new drawing color using static Color objects
g.setColor( Color.blue );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
// display individual RGB values
Color color = Color.magenta;
g.setColor( color );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + color.getRed() + ", " +
color.getGreen() + ", " + color.getBlue(), 130, 115 );
}
}
// execute application
public static void main( String args[] )
{
ShowColors application = new ShowColors();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
}
// end class ShowColors
Applets
• Another class in Swing that inherits from
Component
• Can be executed by any web browser that supports
Java, or Java AppletViewer
– Not a stand-alone application (cf. JFrame)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShowColors extends JApplet {
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
// set new drawing color using integers
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
// set new drawing color using floats
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );
// set new drawing color using static Color objects
g.setColor( Color.blue );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
// display individual RGB values
Color color = Color.magenta;
g.setColor( color );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + color.getRed() + ", " +
color.getGreen() + ", " + color.getBlue(), 130, 115 );
}
} // end class ShowColors
Applets
• Another important difference between applets and
frames is that the sizing and creation of the
window is done in HTML instead of Java.
– What was done through the constructor of the JFrame object
is done for applets through the HTML code:
// this is the file ShowColors.html
<html>
<applet code = "ShowColors.class" width = "400" height = "130">
</applet>
</html>
– We shall simplify our work with applets in this course by
requiring that you always use the JDK appletviewer
• appletviewer ShowColors.html
Readings
• Ch 9