relationships between classes the most common types of relationships: –dependency a class depends...

56
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.

Upload: cecil-jordan

Post on 03-Jan-2016

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 2: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Inheritance

• Motivation– Code reuse

– Conceptual modeling

Page 3: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

How to do inheritance in Java

• Syntaxclass 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

Page 4: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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; } }

Page 5: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 6: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Inheritance class architecture

Undergrad Postgrad

Account

Checking Account

Student

Savings Account

PhDMaster’s

Page 7: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

“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)

Page 8: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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)

Page 9: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 10: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 11: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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; }}

Page 12: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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();

Page 13: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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).

Page 14: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Example

public class Parent { public void meth() // #1 { ... } public void meth(int n) // #2 { ... } ...}public class Offspring extends Parent { public void meth(int n) // #3 { ... } ...}...// in main Parent o1 = new Parent(); Offspring o2 = new Offspring(); o1.meth(); o1.meth(31); o2.meth(); o2.meth(29);

Overloading

Overriding #2

calls #1calls #2calls #1calls #3

Page 15: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Accessing Superclass Memberspublic 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(); } }

Printed in Superclass. Printed in Subclass

Output:

Page 16: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 17: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 18: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 19: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Constructors and Inheritance

public class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

interestRate = 0;

}

}

• the correct solution:

the default constructor from the superclass with 0 parameters will be called automatically.

public class SavingsAccount extends BankAccount{

private double interestRate;

public SavingsAccount(){

super();

interestRate = 0;

}

}

equivalent

Explicitly calling the constructor of the superclass

Q: What if all constructors in the superclass require parameters??

A: Compilation error

Page 20: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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;

}

}

Page 21: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

1. class Student {2. // instance attributes3. private String name;4. private long number;

5. //constructor6. public Student(String aName, long

aNumber){7. name = aName;8. number = aNumber;9. }

10. // instance methods11. 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 attributes3. private String major;4. private int year;

5. //constructor6. public Undergrad(String aName, long

aNumber, String aMajor, int aYear){ 7. super (aName, aNumber);8. setMajor (aMajor);9. setYear(aYear);10. }11. // new methods12. 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

Page 22: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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()); }}

s1 is JohnStudent[name=John,number=202123456]s2 is Marys2 is in year 1Undergrad[name=Mary Ellen,number=201234567,major=ITEC,year=1]

Output:

Page 23: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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 + "]";

}

Page 24: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 25: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 26: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

public class Student{ public Student() { 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 mainUndergrad u = new Undergrad("John", 201234567, "ITEC", 1);

Example

Page 27: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Multiple Layers of Inheritance

• Each ancestor’s constructor is called in turnpublic 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;

}

Page 28: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Converting Between Subclass and Superclass Types

• Converting a subclass type to a superclass typeSavingsAccount 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

Page 29: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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 reusepublic void transfer(double amount, BankAccount other) {

withdraw(amount);

other.deposit(amount);

}

can pass to it any argument of type BankAccount or its subclasses

Page 30: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Converting superclass type reference to subclass type reference

• CastingSavingsAccount savings = (SavingsAccount) anAccount;

This can be dangerous: anAccount is not necessarily a reference to a SavingsAccount object!

• Use instanceof to protect against bad castsif (anAccount instanceof SavingsAccount) {

SavingsAccount savings = (SavingsAccount) anAccount;

}

Page 31: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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 studentsand $150 for students in later years.

Page 32: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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;

}

...

}

Page 33: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

// 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

Page 34: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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”);

Page 35: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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 methodpublic class Coin {

. . .

public boolean equals(Object otherObject) {

Coin other = (Coin) otherObject;

return name.equals(other.getName()) && value.equals(other.getValue());

}

. . .

}

Coin

value

name

Page 36: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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);

}

}

Page 37: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

}

Page 38: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 39: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 40: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 41: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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);

}

}

Page 42: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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); }}

Page 43: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 44: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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 y-

coordinate

Page 45: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Java coordinate system. Units are measured in pixels.

X axis

Y axis

(0, 0)

(x, y)

+x

+y

Page 46: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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 )

Page 47: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Color Control

• Class Color– Defines methods and constants for manipulating colors

– Colors are created from red, green and blue components• RGB values

Page 48: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Color class static constants and RGB values.

Color Constant 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 class static constants and RGB values

Page 49: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Color methods and color-related Graphics methods.

Method Description public Color( int r, int g, int b )

Creates a color based on red, green and blue contents expressed as integers from 0 to 255.

public Color( float r, float g, float b )

Creates a color based on red, green and blue contents expressed 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 content.

public int getBlue() // Color class

Returns a value between 0 and 255 representing the blue content.

public Color getColor() // Graphics class

Returns a Color object representing the current color for the graphics context.

public void setColor( Color c ) // Graphics class

Sets the current color for drawing with the graphics context.

Color methods and color-related Graphics methods.

Page 50: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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.

Page 51: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

import java.awt.*;import java.awt.event.*;// Java extension packagesimport 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 );

Page 52: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

// 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

Page 53: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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)

Page 54: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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

Page 55: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

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:

– We shall simplify our work with applets in this course by requiring that you always use the JDK appletviewer

• appletviewer ShowColors.html

// this is the file ShowColors.html

<html>

<applet code = "ShowColors.class" width = "400" height = "130">

</applet>

</html>

Page 56: Relationships Between Classes The most common types of relationships: –Dependency A class depends on another class if it uses objects of that class. The

Readings

• Ch 9