120 likes | 230 Views
Thinking in Objects. Analogies: Legos, PCs Components Assemblies Defined interfaces and abstraction. Objects and Classes. Class Instance. Behavior and Attributes. Instance variables define object attributes Instance methods are functions that operate on object attributes.
E N D
Thinking in Objects • Analogies: Legos, PCs • Components • Assemblies • Defined interfaces and abstraction Lemay & Perkins [1996]
Objects and Classes • Class • Instance Lemay & Perkins [1996]
Behavior and Attributes • Instance variables define object attributes • Instance methods are functions that operate on object attributes Lemay & Perkins [1996]
Class Creation (1) class Motorcycle { String make; String color; String engineState; void startEngine() { if (engineState == true) System.out.println(“Already on.”); else { engineState = true; System.out.println(“Now on.”); } } } Lemay & Perkins [1996]
Class Creation (2) void showAtts() { System.out.println(“A “ + color + “ “ + make); if (engineState == true) System.out.println(“Engine on.”); else System.out.println(“Engine off.”); } Lemay & Perkins [1996]
Class Creation (3) public static void main(String args[]) { Motorcycle m = new Motorcycle(); m.make = “Yamaha RZ350”; m.color = “yellow”; m.showAtts(); m.startEngine(); m.showAtts(); m.startEngine(); } Lemay & Perkins [1996]
Inheritance • Subclass • Superclass • Inheritance of instance variables and methods Lemay & Perkins [1996]
Class Hierarchy Design Examples • Vehicles (Lemay) • Computers • Sports • Desserts Lemay & Perkins [1996]
Inheritance • Overriding methods • Multiple inheritance prohibited Lemay & Perkins [1996]
Interfaces and Packages • Interface: a collection of methods without definitions, used to indicate special additional methods beyond those inherited by a class from its parent(s) • Packages: a collection of classes and related interfaces • java.lang • Package and class names (e.g., java.awt.Color) Lemay & Perkins [1996]
Subclasses and Subclassing (1) import java.awt.Graphics; import java.awt.Font; import java.awt.Color; public class HelloAgainApplet extends java.applet.Applet { Font f = new Font(“TimesRoman”, Font.BOLD, 36); public void paint(Graphics g) { g.setFont(f); g.setColor(Color.red); g.drawString(“Hi!”, 5, 50); } } Lemay & Perkins [1996]
Subclasses and Subclassing (2) <HTML> <HEAD> <TITLE>Another Applet </TITLE> </HEAD> <BODY> <P>My second Java applet says: <APPLET CODE=“HelloAgainApplet.class” WIDTH=200 HEIGHT=50> </APPLET> </BODY> </HTML> Lemay & Perkins [1996]