Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1.

Slides:



Advertisements
Similar presentations
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
Advertisements

2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Chapter 6 Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and.
Graphical User Interfaces
Made with love, by Zachary Langley Applets The Graphics Presentation.
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Web Design & Development Lecture 19. Java Graphics 2.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Drawing in a frame – Java GUI
AWT Components. 2 Using AWT Components 4 Component –Canvas –Scrollbar –Button –Checkbox –Label –List –Choice –TextComponent –TextArea –TextField 4 Component.
Laboratory Study II October, Java Programming Assignment  Write a program to calculate and output the distance traveled by a car on a tank of.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Interfaces CSC 171 FALL 2004 LECTURE 14. Project 1 review public class Rational { private int numerator, denominator; public Rational(int numerator, int.
Chapter 2 Programming by Example. A Holistic Perspective Three sections separated by blank lines. Program comment File: FileName.java
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
1 Chapter 8 Objects and Classes Lecture 2 Prepared by Muhanad Alkhalisy.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
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 41 Defining Classes and Methods Chapter 4.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
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.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Applets, AWTS CompSci 230 Software Construction.
Writing Classes (Chapter 4)
JAPPLET.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Lesson 27: Introduction to the Java GUI. // helloworldbutton.java import java.awt.*; import javax.swing.*; class HelloButton{ public static void main.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
GUI programming Graphical user interface-based programming.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
© 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.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
1 Applets. 2 Design of Applets 3 Sun wrote Java to be executable within a hosting application browser The applications are applets. An applet is downloaded.
Basics of GUI Programming Chapter 11 and Chapter 22.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
College Board Topics – A.P. Computer Science A Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Java Applets.
Defining Classes and Methods
Java Programming with BlueJ
Chapter 4: Writing classes
Java Applets.
Defining Classes and Methods
Defining Classes and Methods
Presentation transcript:

Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1

Chapter Class and Method Definitions 5.2 Information Hiding and Encapsulation 5.3 Objects and References 5.4 Graphics Supplement 2

5.1 Class and Method Definitions 3 Class Name Instance Variables Methods

Java is Object Oriented 4 It can model any real world object

A class is a blueprint of what an object will look like 5

The object is just an instance of the class 6

Object Oriented Programming deals with the creation of objects 7 and their relationships and interactions

Start by defining the class 8 Car - bodyPaintColor: Color - numberOfTires: int + getBodyPaintColor(): Color + setBodyPaintColor(Color color): void + getNumberOfTires(): int + setNumberOfTires(int tireCount): void Use a UML class diagram instance variables instance methods

Code the class definition 9 public class Car { private Color bodyPaintColor; private int numberOfTires; public Color getPaintColor() { return bodyPaintColor; } // end getPaintColor() public void setPaintColor(Color color) { bodyPaintColor = color; } // end setPaintColor() public int getNumberOfTires() { return numberOfTires; } // end getNumberOfTires() public void setNumberOfTires(int tireCount) { numberOfTires = tireCount; } // end setNumberOfTires() } // end Car instance variables instance methods

An Object consists of data bodyPaintColorColor.Green numberOfTires4 greenCar object's memory footprint

and operations that store and manage the data 11 bodyPaintColorColor.Green numberOfTires4 greenCar bodyPaintColorColor.Red numberOfTires4 redCar Class Car methods methods are shared by all car objects

Each class should be in a separate file 12 public class Car { // code omitted } // end Car Car.java public class Driver { // code omitted } // end Driver Driver.java

new Creates an instance of a class 13 Car myCar = new Car();

Recap  An object is an instance of class  Use new to create an object  Objects have data (instance variables)  Objects offer functionality (methods) 14

There are two types of methods 15 Methods that do not return a value (void) System.out.println("println does not return"); and methods that do return a value int num = keyboard.nextInt();

Let's see how methods work 16 Car myCar = new Car(); First create the object bodyPaintColornull numberOfTires0 myCar Default values

You can then call a method to set an instance variable 17 myCar.setNumberOfTires(4); bodyPaintColornull numberOfTires4 myCar Receiving Object

or a get method to retrieve an instance variable 18 int tireCount = myCar.getNumberOfTires() bodyPaintColornull numberOfTires4 myCar 4

this Demystified 19 public int getNumberOfTires() { return this.numberOfTires; } // end getNumberOfTires() public void setNumberOfTires(int tireCount) { this.numberOfTires = tireCount; } // end setNumberOfTires() Since each method is shared by all the objects, we need to be able to identify the receiving object. this refers to the receiving object, implicitly.

void Method Definition 20 public void setNumberOfTires(int tireCount) { numberOfTires = tireCount; } // end setNumberOfTires() Method is accessible by defining class and any other class Parameter list can be empty or list parameters needed Instance Variable

return Method Definition 21 public int getNumberOfTires() { return numberOfTires; } // end getNumberOfTires() return type of intParameter list can be empty or list parameters needed Instance Variable

Recap  Methods expose a class's functionality  Call a method on a receiving object  this identifies the receiving object inside the method's definition  Each class is stored in its own.java file 22

Local variables are defined within a method 23 public double updateSumAmount(double amount) { double newSumAmount += amount; return newSumAmount; } // end updateSumAmount() local variable

Methods can define same name local variables 24 public void method1() { double someDouble = 0; // Code omitted } // end method1() public void method2() { double someDouble = 0; // Code omitted } // end method2() local to method1 local to method2

5.2 Information Hiding and Encapsulation 25

A method should hide how it is implemented 26 I know what the method does, just not how!

Know "what" a method does, not "how" it does it 27

Methods can be public 28 These define the class's interface

or private 29 These are part of the implementation

Instance Variables are private 30 They define the implementation

Accessor methods control access to instance variables 31 Getters retrieve instance variables Setters set instance variables

Recap  Local variables are defined within a method  Know "what" a method does, not "how" it does it  Public methods define the class's interface  Private instance variables/methods are part of the implementation 32

Class Deconstructed 33 Fraction - numerator: int - denominator: int - reduce(): void + getNumerator(): int + setNumerator(int n): void + getDenominator(): int + setDenominator(int d): void + setNumeratorAndDenominator(int n, int d): void + add(Fraction f): Fraction + subtract(Fraction f): Fraction + multiply(Fraction f): Fraction + divide(Fraction f): Fraction + show(): void

Application Deconstructed package fractiondemo; public class Fraction { private int numerator; private int denominator; 34 private void reduce() { int u = numerator; int v = denominator; int temp; while (v != 0) { temp = u % v; u = v; v = temp; }// end while numerator /= u; denominator /= u; }// end reduce()

Application Deconstructed public int getNumerator() { return numerator; }// end getNumerator() 35 public void setNumerator(int n) { setNumeratorAndDenominator(n, denominator); }// end setNumerator() public int getDenominator() { return denominator; }// end getDenominator() public void setDenominator(int d) { setNumeratorAndDenominator(numerator, d); }// end setDenominator()

Application Deconstructed public void setNumeratorAndDenominator(int n, int d) { numerator = n; if (d == 0) { System.err.println("ERROR: Invalid parameter (" + d + ") in setNumeratorAndDenonimator"); System.exit(1); } else { denominator = d; }// end if }// end setNumeratorAndDenominator() 36 public Fraction add(Fraction f) { Fraction sum = new Fraction(); sum.setNumeratorAndDenominator(numerator * f.denominator + denominator * f.numerator, denominator * f.denominator); sum.reduce(); return sum; }// end add()

Application Deconstructed public Fraction subtract(Fraction f) { Fraction difference = new Fraction(); difference.setNumeratorAndDenominator( numerator * f.denominator - denominator * f.numerator, denominator * f.denominator); difference.reduce(); return difference; }// end subtract() 37 public Fraction multiply(Fraction f) { Fraction product = new Fraction(); product.setNumeratorAndDenominator( numerator * f.numerator, denominator * f.denominator); product.reduce(); return product; }// end multiply()

Application Deconstructed public Fraction divide(Fraction f) { Fraction division = new Fraction(); division.setNumeratorAndDenominator( numerator * f.denominator, denominator * f.numerator); division.reduce(); return division; }// end divide() 38 public void show() { System.out.print("(" + numerator + " / " + denominator + ")"); }// end show() }// end Fraction()

Application Deconstructed package fractiondemo; public class FractionDemo { public static void main(String[] args) { Fraction f1 = new Fraction(); Fraction f2 = new Fraction(); Fraction result = new Fraction(); // Set f1 to 1 / 4. f1.setNumeratorAndDenominator(1, 4); // Set f2 to 1 / 2. f2.setNumeratorAndDenominator(1, 2); 39

Application Deconstructed 40 // Output their sum, difference, product and division. result = f1.add(f2); f1.show(); System.out.print(" + "); f2.show(); System.out.print(" = "); result.show(); System.out.println(); result = f1.subtract(f2); f1.show(); System.out.print(" - "); f2.show(); System.out.print(" = "); result.show(); System.out.println();

Application Deconstructed 41 result = f1.multiply(f2); f1.show(); System.out.print(" * "); f2.show(); System.out.print(" = "); result.show(); System.out.println(); result = f1.divide(f2); f1.show(); System.out.print(" / "); f2.show(); System.out.print(" = "); result.show(); System.out.println(); }// end main() }// end FractionDemo

Application Deconstructed 42

5.3 Objects and References 43

There are two types of variables 44 Value: Stores the actual value 1 Reference: Stores a reference to the actual value 2

Value types store values 45 int x = 100; 100 x

Reference types store references 46 Fraction f = new Fraction(); f numerator ? denominator ?

Lets compare value types 47 int x = 100;x 100 int y = 200;y 200 x == y ? false x = y; x 200 y x == y ?true

Now lets compare reference types 48 f1 == f2 ? false f1 == f2 ?true Fraction f1 = new Fraction(); f1.setNumeratorAndDenominator(1,2); f1 200 numerator 1 denominator Fraction f2 = new Fraction(); f2.setNumeratorAndDenominator(1,2); f2 208 numerator 1 denominator f1 = f2; f1 208 f2 208 numerator 1 denominator 2 208

The solution to the == problem? 49 Define an equals method

Code Deconstructed public boolean equals(Fraction f) { return this.numerator == f.numerator && this.denominator == f.denominator; }// end equals() 50 Two fractions are equal if both their numerator and denominator values are the same.

Code Deconstructed Fraction f1 = new Fraction(); f1.setNumeratorAndDenominator(1, 2); Fraction f2 = new Fraction(); f2.setNumeratorAndDenominator(1, 2); 51 if (f1 == f2) System.out.println("Both variables refer to the same object"); else System.out.println("Each variable refers to a different object"); if ( f1.equals(f2) ) System.out.println("Both objects have the same value"); else System.out.println("Each object has a different value");

Code Deconstructed 52 Fraction f1 = new Fraction(); f1.setNumeratorAndDenominator(1,2); f1 200 numerator 1 denominator Fraction f2 = new Fraction(); f2.setNumeratorAndDenominator(1,2); f2 208 numerator 1 denominator if (f1.equals(f2) {...}... public boolean equals(Fraction f) {...} f2 208 numerator 1 denominator f Both the argument (f2) and the parameter (f) point to the same object. Notice how the parameter (f) refers to the same object as the argument (f2) and thus object can be changed from within the method.

Code Deconstructed 53 Fraction f1 = new Fraction(); f1.setNumeratorAndDenominator(1,2); f1 200 numerator 1 denominator resetFraction(f1);... public void resetFraction(Fraction f) f1 200 numerator 1 denominator f Notice here how the object variable (f) has been assigned a new object, and that f1 stills refers to its original object. { f = new Fraction(); f.setNumeratorAndDenominator(1, 1); } f1 200 numerator 1 denominator f 208 numerator 1 denominator 1 208

5.4 Graphic Supplement 54

Graphics class Revisited 55 The Graphics object defines the client area of the applet window.

Applet Deconstructed package smileyfacemethods; import javax.swing.JApplet; import java.awt.Color; import java.awt.Graphics; public class SmileyFaceMethods extends JApplet { // All the geometric constants remain the same //... 56

Applet public void paint(Graphics canvas) { // Draw a yellow filled face. drawFace(canvas, X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER, Color.YELLOW); // Draw outline in black. drawOutline(canvas, X_FACE, Y_FACE, FACE_DIAMETER, FACE_DIAMETER, Color.BLACK); 57

Applet Deconstructed // Draw a blue left eye. drawEye(canvas, X_LEFT_EYE, Y_LEFT_EYE, EYE_WIDTH, EYE_HEIGHT, Color.BLUE); // Draw a blue right eye. drawEye(canvas, X_RIGHT_EYE, Y_RIGHT_EYE, EYE_WIDTH, EYE_HEIGHT, Color.BLUE); 58

Applet Deconstructed // Draw the black nose. drawNose(canvas, X_NOSE, Y_NOSE, NOSE_DIAMETER, NOSE_DIAMETER, Color.BLACK); // Draw the red mouth. drawMouth(canvas, X_MOUTH, Y_MOUTH, MOUTH_WIDTH, MOUTH_HEIGHT, MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE, Color.RED); }// end paint() 59

Applet Deconstructed private void drawFace(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.fillOval(x, y, width, height); }// end drawFace() 60 private void drawOutline(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.drawOval(x, y, width, height); }// end drawFace()

Applet Deconstructed private void drawEye(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.fillOval(x, y, width, height); }// end drawEye() 61 private void drawNose(Graphics g, int x, int y, int width, int height, Color color) { g.setColor(color); g.fillOval(x, y, width, height); }// end drawNose()

Applet Deconstructed private void drawMouth(Graphics g, int x, int y, int width, int height, int start, int swipe, Color color) { g.setColor(color); g.drawArc(x, y, width, height, start, swipe); }// end drawNose() }// end SmileyFaceMethods 62

Applet Deconstructed 63

init() Vs. paint() 64

Both have a place in Applets  An applet could have both an init() and paint() or neither (unusual)  Both get called automatically  Paint() repaints controls as needed  Init() initialization before applet starts 65

Code Deconstructed 66 import javax.swing.JLabel;... JLabel firstNameLabel = new JLabel("First name: "); JLabel lastNameLabel = new JLabel("Last name: "); A label is a control for displaying static text in an applet or frame. Create and add the label in the init() method

Code Deconstructed 67 import java.awt.Container;... Container contentPane = getContentPane(); A Container is a control that can contain other controls The applet's ContentPane is one such container

Code Deconstructed 68 import java.awt.FlowLayout;... contentPane.setLayout( new FlowLayout() ); contentPane.add(firstNameLabel); contentPane.add(lastNameLabel); A FlowLayout control helps in laying out the controls in a container Each container can be associated with a FlowLayout.

Application Deconstructed package labelsdemo; import javax.swing.JLabel; import javax.swing.JFrame; import java.awt.Container; import java.awt.FlowLayout; public class LabelsDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JLabel salutationLabel = new JLabel("Hello there,"); JLabel nameLabel = new JLabel("Mr. Magoo!"); Container contentPane = frame.getContentPane(); 69

Application Deconstructed contentPane.setLayout( new FlowLayout() ); contentPane.add(salutationLabel); contentPane.add(nameLabel); frame.setSize(200, 100); frame.setVisible(true); } 70

Application Deconstructed 71

Application Deconstructed package labelsappletdemo; import javax.swing.JLabel; import javax.swing.JApplet; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; public class LabelsAppletDemo extends JApplet { private void drawString(Graphics g, String string, int x, int y) { g.drawString(string, x, y); }// end drawString() 72

Application public void init() { JLabel salutationLabel = new JLabel("Hello there,"); JLabel nameLabel = new JLabel("Mr Magoo!"); Container contentPane = getContentPane(); contentPane.setLayout( new FlowLayout() ); contentPane.add(salutationLabel); contentPane.add(nameLabel); }// end init() 73 The init() method executes once before applet starts. It displays the two labels, but they do not remain visible for long.

Application public void paint(Graphics g) { drawString(g, "Hello to you too!", 50, 100); }// end paint() }// end LabelsAppletDemo 74 The paint() method is then executed and repaints the applet's content pane and draws the string. Notice how the labels never have a chance!