1 Even even more on being classy Aaron Bloomfield CS 101-E Chapter 4+

Slides:



Advertisements
Similar presentations
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Advertisements

Written by: Dr. JJ Shepherd
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
Chapter 3 - Java Programming With Supplied Classes1 Chapter 3 Java Programming With Supplied Classes.
Road Map Introduction to object oriented programming. Classes
CS102 Data Types in Java CS 102 Java’s Central Casting.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Using Objects CS 101-E Aaron Bloomfield. Announcements Midterm 1 is a week from this Wednesday Midterm 1 is a week from this Wednesday TESTS ARE IN CHM.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
UML Basics & Access Modifier
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.,
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Chapter 2: Java Fundamentals
© A+ Computer Science - Chicken yeller = new Chicken();
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 5: Ball Worlds Features 2 classes, constant data fields, constructors, extension through inheritance, graphics.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Data Types and Operations On Data Objective To understand what data types are The need to study data types To differentiate between primitive types and.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
Applications Development
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6: Transition to Java Programming with Alice and Java First Edition.
Computer Science 209 The Adapter Pattern. The Context of the Adapter Pattern I want to use an existing class (the adaptee) without modifying it The context.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
Classes. Preparation Scene so far has been background material and experience –Computing systems and problem solving –Variables –Types –Input and output.
Using classes. One step instantiation, Composition I JFrame myWindow = new JFrame( ); Two step Instantiation, Composition II private JFrame myWindow;
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Written by: Dr. JJ Shepherd
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Review for exam 1 CS 101 Aaron Bloomfield. 2 Today’s lecture An overview of the “review” sections of chapters 1-3 Stop me if you want me to go over.
Java exercise review Lesson 26: Exercise 4. Exercise #4 – a sample solution 1.Write the psudocode and the deployment diagram for what you are planning.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
1 Review for Midterm 2 Aaron Bloomfield CS 101-E.
Introducing, the JFrame Gives us a work area beside System.out.println.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Review of Java … or maybe not.
Yanal Alahmad Java Workshop Yanal Alahmad
Exercise on Java Basics
5 Variables, Data Types.
Introduction to Java Programming
Java Classes and Objects 3rd Lecture
A+ Computer Science METHODS.
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Grouped Data Arrays, and Array Lists.
A+ Computer Science METHODS.
Classes.
Classes.
Presentation transcript:

1 Even even more on being classy Aaron Bloomfield CS 101-E Chapter 4+

2 Consider this sequence of events…

3 What happened? Java didn’t “repaint” the rectangles when necessary Java didn’t “repaint” the rectangles when necessary Java only painted the rectangle once Java only painted the rectangle once You can tell Java to repaint it whenever necessary You can tell Java to repaint it whenever necessary This is beyond the scope of this class, though! This is beyond the scope of this class, though!

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

5 Seeing double When paint() was called, the previous rectangle was not erased When paint() was called, the previous rectangle was not erased This is a simpler way of implementing this This is a simpler way of implementing this Perhaps clear and repaint everything when a rectangle paint() is called Perhaps clear and repaint everything when a rectangle paint() is called

6 // Purpose: Create two windows containing colored rectangles. import java.util.*; public class BoxFun { //main(): application entry point public static void main (String[] args) { ColoredRectangle r1 = new ColoredRectangle(); ColoredRectangle r2 = new ColoredRectangle(); System.out.println("Enter when ready"); Scanner stdin = new Scanner (System.in); stdin.nextLine(); r1.paint(); // draw the window associated with r1 r2.paint(); // draw the window associated with r2 }} Code from last class

7 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() { color = Color.BLUE; width = 40; x = 80; height = 20;y = 90; window = new JFrame("Box Fun"); window.setSize(200, 200); 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); }}

8 String - text = “Box Fun” length() : int setVisible (boolean status) : void + getGraphics () : Graphics + setSize (int w, int h) : void + … JFrame - width = height = title = - grafix = -... Graphics - … + setColor(Color) : void fillRect() : void r + paint() : void ColorRectangle - width = 0 - height = 0 - x = 0 - y = 0 - color = - window = Color - color = brighter() : Color +... ColoredRectangle r = new ColoredRectangle(); + paint() : void ColorRectangle - width = 40 - height = 20 - x = 80 - y = 90 - color = - window = public class ColoredRectangle { private int width; private int x, y; private int height; private int y; private JFrame window; private Color color; public ColoredRectangle() { color = Color.BLUE; color = Color.BLUE; width = 40; width = 40; height = 20; height = 20; y = 90; y = 90; x = 80; x = 80; window = new window = newJFrame ("Box Fun"); window.setSize window.setSize (200, 200); window.setVisible window.setVisible(true);} public void paint() { Graphics g = Graphics g = window.getGraphics(); window.getGraphics(); g.setColor(color); g.setColor(color); g.fillRect (x, y, g.fillRect (x, y, width, height); width, height);} g

9 The Vector class In java.util In java.util Must put “import java.util.*;” in the java file Must put “import java.util.*;” in the java file Probably the most useful class in the library (in my opinion) Probably the most useful class in the library (in my opinion) A Vector is a collection of “things” (objects) A Vector is a collection of “things” (objects) It has nothing to do with the geometric vector It has nothing to do with the geometric vector

10 Vector methods Constructor: Vector() Constructor: Vector() Adding objects: add (Object o); Adding objects: add (Object o); Removing objects: remove (int which) Removing objects: remove (int which) Number of elements: size() Number of elements: size() Element access: elementAt() Element access: elementAt() Removing all elements: clear() Removing all elements: clear()

11 Vector code example Vector v = new Vector(); System.out.println (v.size() + " " + v); v.add ("first"); System.out.println (v.size() + " " + v); v.add ("second"); v.add ("third"); System.out.println (v.size() + " " + v); String s = (String) v.elementAt (2); System.out.println (s); String t = (String) v.elementAt (3); System.out.println (t); v.remove (1); System.out.println (v.size() + " " + v); v.clear(); 0 [] 1 [first] 3 [first, second, third] third(Exception) 2 [first, third] 0 []

12 What we wish computers could do

13 The usefulness of Vectors You can any object to a Vector You can any object to a Vector Strings, ColoredRectanges, JFrames, etc. Strings, ColoredRectanges, JFrames, etc. They are not the most efficient for some tasks They are not the most efficient for some tasks Searching, in particular Searching, in particular

14 About that exception… The exact exception was: The exact exception was: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 >= 3 at java.util.Vector.elementAt(Vector.java:431) at java.util.Vector.elementAt(Vector.java:431) at VectorTest.main(VectorTest.java:15) at VectorTest.main(VectorTest.java:15) Where the problem occured

15 A Vector of ints Consider the following code: Consider the following code: Vector v = new Vector(); v.add (1); Causes a compile-time error Causes a compile-time error Most of the time - see disclaimer later Most of the time - see disclaimer later C:\Documents and Settings\Aaron\My Documents\JCreator\VectorTest\VectorTest.java:7: cannot resolve symbol symbol : method add (int) location: class java.util.Vector v.add (1);

16 What happened? The Vector add() method: The Vector add() method: boolean add(Object o) boolean add(Object o) Primitive types are not objects! Primitive types are not objects! Solution: use wrapper classes! Solution: use wrapper classes!

17 More on wrapper classes A wrapper class allows a primitive type to act as an object A wrapper class allows a primitive type to act as an object Each primitive type has a wrapper class: Each primitive type has a wrapper class: Boolean Boolean Character Character Byte Byte Short Short Note that char and int don’t have the exact same name as their wrapper classes Note that char and int don’t have the exact same name as their wrapper classes Integer Integer Long Long Float Float Double Double

18 Vector code example Vector v = new Vector(); System.out.println (v.size() + " " + v); v.add (new Integer(1)); System.out.println (v.size() + " " + v); v.add (new Integer(2)); v.add (new Integer(3)); System.out.println (v.size() + " " + v); Integer s = (Integer) v.elementAt (2); System.out.println (s); Integer t = (Integer) v.elementAt (3); System.out.println (t); v.remove (1); System.out.println (v.size() + " " + v); v.clear(); 0 [] 1 [1] 3 [1, 2, 3] 3(Exception) 2 [1, 3] 0 []

19 Even more on wrapper classes They have useful class (i.e. static) variables: They have useful class (i.e. static) variables: Integer.MAX_VALUE Integer.MAX_VALUE Double.MIN_VALUE Double.MIN_VALUE They have useful methods: They have useful methods: String s = “ ”; String s = “ ”; double d = Double.parseDouble (s); double d = Double.parseDouble (s);

20 A disclaimer Java 1.5 (which we are not using) has a new feature called “autoboxing/unboxing” Java 1.5 (which we are not using) has a new feature called “autoboxing/unboxing” This will automatically convert primitive types to their wrapper classes (and back) This will automatically convert primitive types to their wrapper classes (and back)

21 An optical illusion

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

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

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

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

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

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

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

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

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

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

32 Ugh…

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

34 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 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 A change to a static variable is visible to all of the objects in the class Examples StaticDemo.java and DemoStatic.java Examples StaticDemo.java and DemoStatic.javaStaticDemo.javaDemoStatic.javaStaticDemo.javaDemoStatic.java

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

36 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.java Example AirConditionerConstruction.javaAirConditionerConstruction.java

37 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.java Example TurnDemo.javaTurnDemo.java

38 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.java Example AirConditionerAccessors.javaAirConditionerAccessors.java

39 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.java Example AirConditionerSetMutation.javaAirConditionerSetMutation.java

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

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

42 What computers were made for NASA’s WorldWind NASA’s WorldWind NASA’s WorldWind NASA’s WorldWind See See