Classes. Preparation Scene so far has been background material and experience –Computing systems and problem solving –Variables –Types –Input and output.

Slides:



Advertisements
Similar presentations
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Advertisements

Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
© 2004 Pearson Addison-Wesley. All rights reserved2-1 Introduction to Graphics The last few sections of each chapter of the textbook focus on graphics.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 A Simple Applet. 2 Applets and applications An application is an “ordinary” program Examples: Notepad, MS Word, Firefox, Halo, etc. An applet is a Java.
©2004 Brooks/Cole Applets Graphics & GUIs. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Graphical Programs Most applications these days are.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
2D Graphics in Java COMP53 Nov 14, Applets and Applications Java applications are stand-alone programs – start execution with main() – runs in JVM.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Java Applets What is an Applet? How do you create.
ObjectDraw and Objects Early Chris Nevison Barbara Wells.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Applets and Graphics.
A Simple Applet. Applets and applications An applet is a Java program that runs on a web page –Applets can be run from: Internet Explorer Netscape Navigator.
Chapter 3 - Introduction to Java Applets Outline 3.1Introduction 3.2Thinking About Objects 3.4A Simple Java Applet: Drawing a String 3.5Two More Simple.
A Simple Applet.
Chapter 5 Graphics. Topics Applets Classes used for graphics –Graphics –Point –Dimension –Color.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Drawing pictures with Java. JFrame: the basic Java window The swing package contains classes, objects and methods that can be used to create a consistent.
Java Programs u 1 project file –with an extension of.mcp –contains information that CodeWarrior needs to run the program u >= 1 source files –have an extension.
Object-Oriented Programming in Java. Object-Oriented Programming Objects are the basic building blocks in an O-O program. – A program consists of one.
1 Classes CS 101-E Chapter 4 Aaron Bloomfield. 2 Announcements  HWs are being renumbered J1, J2, etc., for Java programming assignments C1, C2, etc.,
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Java Applets What is an Applet? How do you create.
1 Classes Chapter 4 Spring 2005 CS 101 Aaron Bloomfield.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
METHODS AND SCOPE CSCE More on Methods  This is chapter 6 in Small Java.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
GUI programming Graphical user interface-based programming.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
Applets Applet is java program that can be embedded into HTML pages. Java applets runs on the java enabled web browsers such as mozilla and internet explorer.
1 A Simple Applet. 2 Applets and applications An application is an “ordinary” program Examples: Notepad, MS Word, Firefox, Halo, etc. An applet is a Java.
© A+ Computer Science - Chicken yeller = new Chicken();
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Even even more on being classy Aaron Bloomfield CS 101-E Chapter 4+
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Graphics and Java2D Chapter Java Coordinate System Origin is in _____________ corner –Behind title bar of window X values increase to the ________.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Using classes. One step instantiation, Composition I JFrame myWindow = new JFrame( ); Two step Instantiation, Composition II private JFrame myWindow;
1 A Simple Applet. 2 Applets and applications An applet is a Java program that runs on a web page Applets can be run within any modern browser To run.
GUI Components. The Swing package has numerous GUI components that can be added to a window. The Swing package has numerous GUI components that can be.
Lecture 3.1 Using Graphics with JFrame. © 2006 Pearson Addison-Wesley. All rights reserved javax.swing.JFrame - int x - int y - int width - int.
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
Week 3 Object-oriented programming JOptionPane Random Graphics.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Recitations Sep 8-9 u conditionals: if-else statement u boolean expressions u classes and instances.
1 Sections 5.1 – 5.2 Digital Image Processing Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
6.1 Coordinates The screen of a computer is a grid of little squares called pixels. The color of each pixel can be set individually, and drawing on the.
Introducing, the JFrame Gives us a work area beside System.out.println.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
Break Time! Graphical User Interface (GUI) NO EXAM….ONLY PROJECT!
A structured walkthrough
Chapter 3 Syntax, Errors, and Debugging
Object Oriented Programming
Basic Graphics Chapter 5 3/19/15 Thursday Section Only
Example: Card Game Create a class called “Card”
Graphical user interface-based programming
CIS 199 Final Review.
Classes.
Classes.
Presentation transcript:

Classes

Preparation Scene so far has been background material and experience –Computing systems and problem solving –Variables –Types –Input and output –Expressions –Assignments –Objects –Standard classes and methods

Ready Experience what Java is really about –Design and implement objects representing information and physical world objects

Object-oriented programming Basis –Create and manipulate objects with attributes and behaviors that the programmer can specify Mechanism –Classes Benefits –An information type is design and implemented once and reused as needed No need reanalysis and re-justification of the representation

Design an air conditioner representation Context Behaviors Attributes

Design an air conditioner representation Context –Repair person –Sales person –Consumer Behaviors Attributes

Design an air conditioner representation Context – Consumer Behaviors Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting –Set temperature and fan setting –Build – construction –Debug Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting –Set temperature and fan setting –Build – construction –Debug – to stringing Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting –Set temperature and fan setting – mutation –Build – construction –Debug – to stringing Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting – accessing –Set temperature and fan setting – mutation –Build – construction –Debug – to stringing Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on – mutation –Turn off – mutation –Get temperature and fan setting – accessing –Set temperature and fan setting – mutation –Build – construction –Debug – to stringing Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on – mutation –Turn off – mutation –Get temperature and fan setting – accessing –Set temperature and fan setting – mutation –Build – construction –Debug – to stringing Attributes

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting –Set temperature and fan setting –Build -- construction –Debug Attributes –Power setting –Fan setting –Temperature setting

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting –Set temperature and fan setting –Build -- construction –Debug Attributes –Power setting –Fan setting –Temperature setting – integer

Design an air conditioner representation Context - Consumer Behaviors –Turn on –Turn off –Get temperature and fan setting –Set temperature and fan setting –Build -- construction –Debug Attributes –Power setting – binary –Fan setting – binary –Temperature setting – integer

Design an air conditioner representation // Represent an air conditioner – from consumer view point public class AirConditioner { // instance variables // constructors // methods } Source AirConditioner.javaAirConditioner.java

Static variables and constants // shared resource for all AirConditioner objects static public final int OFF = 0; Static public final int ON = 1; static public final int LOW = 0; Static public final int HIGH = 1; static public final int DEFAULT_TEMP = 72; Every object in the class has access to the same static variables and constants –A change to a static variable is visible to all of the objects in the class –Examples StaticDemo.java and DemoStatic.javaStaticDemo.javaDemoStatic.java

Instance variables // individual object attributes int powerSetting; int fanSetting; int temperatureSetting; Instance variables are always initialized as soon the object comes into existence –If no value is specified 0 used for numeric variables false used for logical variables null used for object variables Examples InitializeDemo.javaInitializeDemo.java

Constructors // AirConditioner(): default constructor public AirConditioner() { this.powerSetting = AirConditioner.OFF; this.fanSetting = AirConditioner.LOW; this.temperatureSetting = AirConditioner.DEFAULT_TEMP; } // AirConditioner(): specific constructor public AirConditioner(int myPower, int myFan, int myTemp) { this.powerSetting = myPower; this.fanSetting = myFan; this.temperatureSetting = myTemp; } Example AirConditionerConstruction.javaAirConditionerConstruction.java

Simple mutators // turnOn(): set the power setting to on public void turnOn() { this.powerSetting = AirConditioner.ON; } // turnOff(): set the power setting to off public void turnOff() { this.powerSetting = AirConditioner.OFF; } Example TurnDemo.javaTurnDemo.java

Simple accessors // getPowerStatus(): report the power setting public int getPowerStatus() { return this.powerSetting; } // getFanStatus(): report the fan setting public int getFanStatus() { return this.fanSetting; } // getTemperatureStatus(): report the temperature setting public int getTemperatureStatus () { return this.temperatureSetting; } Example AirConditionerAccessors.javaAirConditionerAccessors.java

Parametric mutators // setPower(): set the power setting as indicated public void setPower(int desiredSetting) { this.powerSetting = desiredSetting; } // setFan(): set the fan setting as indicated public void setFan(int desiredSetting) { this.fanSetting = desiredSetting; } // setTemperature(): set the temperature setting as indicated public void setTemperature(int desiredSetting) { this.temperatureSetting = desiredSetting; } Example AirConditionerSetMutation.javaAirConditionerSetMutation.java

Facilitator toString() // toString(): produce a String representation of the object public String toString() { String result = "[ power: " + this.powerSetting + ", fan: " + this.fanSetting + ", temperature: " + this.temperatureSetting + " ] "; return result; }

Sneak peek facilitator toString() public String toString() { String result = "[ power: " ; if ( this.powerSetting == AirConditioner.OFF ) { result = result + "OFF"; } else { result = result + "ON " ; } result = result + ", fan: "; if ( this.fanSetting == AirConditioner.LOW ) { result = result + "LOW "; } else { result = result + "HIGH"; } result = result + ", temperature: " + this.temperatureSetting + " ]"; return result; }

ColoredRectangle Purpose –Represent a colored rectangle in a window –Introduce the basics of object design and implementation

Background JFrame –Principal Java class for representing a titled, bordered graphical window. –Standard class Part of the swing library import javax.swing.* ;

Example Consider JFrame w1 = new JFrame("Bigger"); JFrame w2 = new JFrame("Smaller"); w1.setSize(200, 125); w2.setSize(150, 100); w1.setVisible(true); w2.setVisible(true);

Example Consider JFrame w1 = new JFrame("Bigger"); JFrame w2 = new JFrame("Smaller"); w1.setSize(200, 125); w2.setSize(150, 100); w1.setVisible(true); w2.setVisible(true);

Example Consider JFrame w1 = new JFrame("Bigger"); JFrame w2 = new JFrame("Smaller"); w1.setSize(200, 125); w2.setSize(150, 100); w1.setVisible(true); w2.setVisible(true);

Example Consider JFrame w1 = new JFrame("Bigger"); JFrame w2 = new JFrame("Smaller"); w1.setSize(200, 125); w2.setSize(150, 100); w1.setVisible(true); w2.setVisible(true);

Class ColoredRectangle – initial version Purpose –Support the display of square window containing a blue filled-in rectangle Window has side length of 200 pixels Rectangle is 40 pixels wide and 20 pixels high Upper left hand corner of rectangle is at (80, 90) –Limitations are temporary Remember BMI.java preceded BMICalculator.java Lots of concepts to introduce

ColoredRectangle in action Consider ColoredRectangle r1 = new ColoredRectangle(); ColoredRectangle r2 = new ColoredRectangle(); System.out.println("Enter when ready"); System.in.read(); r1.paint(); // draw the window associated with r1 r2.paint(); // draw the window associated with r2

ColoredRectangle in action Consider ColoredRectangle r1 = new ColoredRectangle(); ColoredRectangle r2 = new ColoredRectangle(); System.out.println("Enter when ready"); System.in.read(); r1.paint(); // draw the window associated with r1 r2.paint(); // draw the window associated with r2

ColoredRectangle in action Consider ColoredRectangle r1 = new ColoredRectangle(); ColoredRectangle r2 = new ColoredRectangle(); System.out.println("Enter when ready"); System.in.read(); r1.paint(); // draw the window associated with r1 r2.paint(); // draw the window associated with r2

ColoredRectangle in action Consider ColoredRectangle r1 = new ColoredRectangle(); ColoredRectangle r2 = new ColoredRectangle(); System.out.println("Enter when ready"); System.in.read(); r1.paint(); // draw the window associated with r1 r2.paint(); // draw the window associated with r2

ColoredRectangle.java outline import javax.swing.*; import java.awt.*; public class ColoredRectangle { // instance variables for holding object attributes private int width; private int height; private int x; private int y; private JFrame window; private Color color; // ColoredRectangle(): default constructor public ColoredRectangle() { //... } // paint(): display the rectangle in its window public void paint() { //... }

Instance variables and attributes Data field –Java term for an object attribute Instance variable –Symbolic name for a data field –Usually has private access Assists in information hiding by encapsulating the object’s attributes –Default initialization Numeric instance variables initialized to 0 Logical instance variables initialized to false Object instance variables initialized to null

public class ColoredRectangle { // instance variables for holding object attributes private int width; private int x; private int height; private int y; private JFrame window; private Color color; // ColoredRectangle(): default constructor public ColoredRectangle() { window = new JFrame("Box Fun"); window.setSize(200, 200); width = 40; x = 80; height = 20;y = 90; color = Color.BLUE; window.setVisible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window.getGraphics(); g.setColor(color); g.fillRect(x, y, width, height); }

public class ColoredRectangle { // instance variables for holding object attributes private int width; private int x; private int height; private int y; private JFrame window; private Color color; // ColoredRectangle(): default constructor public ColoredRectangle() { window = new JFrame("Box Fun"); window.setSize(200, 200); width = 40; x = 80; height = 20;y = 90; color = Color.BLUE; window.setVisible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window.getGraphics(); g.setColor(color); g.fillRect(x, y, width, height); }

ColoredRectangle default constructor

public class ColoredRectangle { // instance variables for holding object attributes private int width; private int x; private int height; private int y; private JFrame window; private Color color; // ColoredRectangle(): default constructor public ColoredRectangle() { window = new JFrame("Box Fun"); window.setSize(200, 200); width = 40; x = 80; height = 20;y = 90; color = Color.BLUE; window.setVisible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window.getGraphics(); g.setColor(color); g.fillRect(x, y, width, height); }

Color constants Color.BLACK Color.BLUE Color.CYAN Color.DARK_GRAY Color.GRAY Color.GREEN Color.LIGHT_GRAY Color.MAGENTA Color.ORANGE Color.PINK Color.RED Color.WHITE Color.YELLOW

public class ColoredRectangle { // instance variables for holding object attributes private int width; private int x; private int height; private int y; private JFrame window; private Color color; // ColoredRectangle(): default constructor public ColoredRectangle() { window = new JFrame("Box Fun"); window.setSize(200, 200); width = 40; x = 80; height = 20;y = 90; color = Color.BLUE; window.setVisible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window.getGraphics(); g.setColor(color); g.fillRect(x, y, width, height); }

Graphical context Graphics –Defined in java.awt.Graphics –Represents the information for a rendering request Color Component Font … –Provides methods –Text drawing Line drawing Shape drawing –Rectangles –Ovals –Polygons

Java coordinate system

public class ColoredRectangle { // instance variables for holding object attributes private int width; private int x; private int height; private int y; private JFrame window; private Color color; // ColoredRectangle(): default constructor public ColoredRectangle() { window = new JFrame("Box Fun"); window.setSize(200, 200); width = 40; x = 80; height = 20;y = 90; color = Color.BLUE; window.setVisible(true); } // paint(): display the rectangle in its window public void paint() { Graphics g = window.getGraphics(); g.setColor(color); g.fillRect(x, y, width, height); }

Method invocation Consider r1.paint(); // display window associated with r1 r2.paint(); // display window associated with r2 Observe –When an instance method is being executed, the attributes of the object associated with the invocation are accessed and manipulated –Important that you understand what object is being manipulated

Method invocation

Improving ColoredRectangle Analysis –A ColoredRectangle object should Be able to have any color Be positionable anywhere within its window Have no restrictions on its width and height Accessible attributes Updateable attributes

Improving ColoredRectangle Additional constructions and behaviors –Specific construction Construct a rectangle representation using supplied values for its attributes –Accessors Supply the values of the attributes Individual methods for providing the width, height, x- coordinate position, y-coordinate position, color, or window of the associated rectangle –Mutators Manage requests for changing attributes Ensure objects always have sensible values Individual methods for setting the width, height, x- coordinate position, y-coordinate position, color, or window of the associated rectangle to a given value

A mutator method Definition // setWidth(): width mutator public void setWidth(int w) { width = w; } Usage

Mutator setWidth() evaluation

Subtleties Consider ColoredRectangle r = new ColoredRectangle(); r.paint(); r.setWidth(80); r.paint(); What is the width is the rectangle on the screen after the mutator executes?

Other mutators public void setHeight(int h) { height = h; } public void setX(int ulx) { x = ulx; } public void setY(int uly) { y = uly; } public void setWindow(JFrame f) { window = f; } public void setColor(Color c) { color = c; }

Mutator usage

Accessors Properties –Do not require parameters –Each accessor execution produces a return value Return value is the value of the invocation

Accessor usage

Specific construction public ColoredRectangle(int w, int h, int ulx, int uly, JFrame f, Color c) { setWidth(w); setHeight(h); setX(ulx); setY(uly); setWindow(f); setColor(c); } Requires values for each of the attributes JFrame display = new JFrame("Even more fun"); display.setSize(400, 400); ColoredRectangle w = new ColoredRectangle(60, 80, 20, 20, display, Color.YELLOW);

Specific construction public ColoredRectangle(int w, int h, int ulx, int uly, JFrame f, Color c) { setWidth(w); setHeight(h); setX(ulx); setY(uly); setWindow(f); setColor(c); } Advantages to using mutators –Readability –Less error prone –Facilitates enhancements through localization

Seeing double import java.io.*; import java.awt.*; public class SeeingDouble { public static void main(String[] args) throws IOException { ColoredRectangle r = new ColoredRectangle(); System.out.println("Enter when ready"); System.in.read(); r.paint(); r.setY(50); r.setColor(Color.RED); r.paint(); }

Seeing double