An Introduction to
Computer Science with Java
Copyright 2013 by C. Herbert, all rights reserved.
Last edited August 21, 2013 by C. Herbert
This document is a draft of a chapter from Computer Science with Java, written by Charles Herbert with the assistance of Craig
Nelson. It is available free of charge for students in Computer Science 111 at Community College of Philadelphia during the Fall
2013 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
CSCI 111 Chapter 11 Graphics pg. 2
Introduction to
Computer Science with Java
Chapter 11 – Java Graphics
This short chapter describes how programmers can create and manipulate two-dimensional graphics in
Java. It includes creating.
Chapter Learning Outcomes
Upon completion of this chapter students should be able to:
Describe what a graphics processing unit (GPU) is and why GPUs are used
with modern computers.
Describe what the java.awt.Canvas and java.awt.Graphics classes are and
how they are used.
Describe how to do each of the following using the Java Graphics class:
o setting the Color for graphics;
o drawing lines;
o drawing rectangles, and rectangles with rounded corners;
o drawing ovals, circles, and arc of ovals and circles;
o drawing polygons;
o drawing text on the screen.
Describe how to create graphs and charts illustrating business and scientific data.
Create software that uses the Java Graphics class to create figurative and abstract images.
11.1 Overview of Graphics Programming in Java
Graphics programming in Java is done through the use of APIs, including the java.awt.Graphics class and
the Java 2D API that are both part of AWT; Java OpenGL (JOGL), Java 3D (J3D), and Java Advanced
Imaging (JAI), which are official Java APIs; and many third party APIs, such as the Java LightWeight
Game Library (JLWGL). The graphics capabilities in the AWT and the Java OpenGL graphics libraries are
by far the most commonly used.
In this chapter we will focus on creating simple graphics and concepts of graphics programming using
the graphics classes included in AWT, which will allow us to create and manipulate simple graphic
images that can be displayed using the same containers as those used for Swing components.
The graphics capabilities in AWT should work equally as well on Windows, Mac and Linux-based
systems, although specialized coding for certain devices and unique hardware configurations may
require the use of specialized APIs.
CSCI 111 Chapter 11 Graphics pg. 3
Generally, instructions in Java, as in any programming language are fed through the operating system to
the computer’s hardware. In the case of graphics programming, an additional component is often
present – a graphics processing unit. A graphics processing unit (GPU), often called a graphics
accelerator, is a specialized processing unit for rendering high quality im ...
Applications use in Java GUIThe Java GUI consists of a separate, .pdfakshay1213
Applications use in Java GUI:
The Java GUI consists of a separate, automous task execution thread called the \"event loop\".
Every action that affects the GUI, e.g. calls to repaint the screen or to manipulate the properties
of a GUI component, or is a result of something happening to the GUI, e.g. the user clicks the
mouse or hits a key, is encapsulated in the form of an \"event\" that is placed into a queue for the
event loop to process. The result of processing an event may be a manipulation of the bits of
color on the screen or it may result in calls to methods in the developer\'s code.
1.A Java GUI application uses the standard Java components GUI component set, Swing, and is
deployed to the desktop.
2.The Swing GUI Builder in NetBeans IDE simplifies the GUI development process and enables
you to visually create Java GUI applications using pre-installed Swing and AWT components.
3.JavaFX is a rich set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications (RIAs) that behave consistently across multiple
platforms.
Similariti Between JAVA and JAVA GUI:
I think in many cases the overhead incurred to run a JVM is acceptable because of the
functionality the code base
provides.So winding back a bit, the reason that functionality can exist with Java has much to do
with the language/environment which frees programmers from a lot of resource management and
allows them to focus
more on plugging together components. Time to market and all that jazz.Like a lot of interpreted
languages, Java\'s development cycle ispretty excellent I think. A programmer can get a fairly
complicatedapplication off the ground quickly due to a number of things broughtabout both by
the interp-language development paradigm that allows for
immediate detection of errors and compile-and-test-as-you-code sessions.I think those are the
kinds of things which has made Java popular.
Some Java applications that you can install and play with on your own desktop machine:
1.Eclipse
2.NetBeans
3.jEdit
4.OpenOffice
Java is used in
JAVA GUI:
The Java GUI system however is a legacy issue where the system underwent a large-scale
upgrade , so some of the classes involved are spread over the (relatively) older java.awt packages
and the newer javax.swing packages. In general, if the class name starts with \"J\", then it is in
the Swing package. Since some functionality appears to be duplicated in the Swing packages,
such as frames and buttons, always use the Swing component over the older AWT components
when there is a choice.
Commonly Used Methods in GUI Components:
void setPreferredSize(int width, int height) :sets the size of a component to be used when the
layout manager is able to use that size, e.g. there is enough room. Some layout managers always
ignore the size setting of a component because the size is under other constraints..
String getText(), void setText(String s) :accessor methods for the text of labels, button.
Implementation of embedded arm9 platform using qt and open cv for human upper...Krunal Patel
: In this Paper, A novel architecture for automotive vision using an embedded device will be
implemented on ARM9 Board with highly computing capabilities and low processing power. Currently,
achieving real-time image processing routines such as convolution, thresholding, edge detection and some of the
complex media applications is a challenging task in embedded Device, because of limited memory. An open
software framework, Linux OS is used in embedded devices to provide a good starting point for developing the
multitasking kernel, integrated with communication protocols, data management and graphical user interface for
reducing the total development time. To resolve the problems faced by the image processing applications in
embedded Device a new application environment was developed. This environment provides the resources
available in the operating system which runs on the hardware with complex image processing libraries. This
paper presents the capture of an image from the USB camera, applied to image processing algorithms to Detect
Human Upper Body. The application (GUI) Graphical User Interface was designed using Qt and ARM Linux
gcc Integrated Development Environment (IDE) for implementing image processing algorithm using Open
Source Computer Vision Library (OpenCV). This developed software integrated in mobiles by the cross
compilation of Qt and the OpenCV software for Linux Operating system. The result utilized by Viola and Jones
Algorithm with Haar Features of the image using OpenCV.
An API is a set of routines and protocols that allows software developers to build applications. It provides standard ways to develop applications that will work within an operating system. Popular 3D graphics APIs like OpenGL and Direct3D define standard pipelines that graphics hardware uses to process 3D scenes and convert them into 2D images for display. The graphics pipeline involves several stages including clipping, lighting, texturing, rasterization, and display.
This document discusses Java graphics and input/output. It introduces the Graphics class in Java AWT which is used to draw on components. It describes various Graphics methods like drawString, drawRect. It also discusses AWT event handling and different event classes. Finally, it covers Java I/O streams like InputStream, OutputStream and file streams like FileInputStream and FileOutputStream along with methods to read and write from files.
The document discusses visualization systems and proposes concepts for their future development. It summarizes:
1) The "Visual Realityware" visualization software development environment, which uses an abstraction layer to allow developers to freely select mainstream graphics technologies and expand applications across multiple platforms with minimal bugs.
2) An application called "Virtual Anatomia" developed using Visual Realityware to visualize 3D biological data in real-time.
3) The concept of "Visionize" which is defined as a risk management methodology using visual communication to allow sharing of goals and visions in order to identify and prevent risks before issues arise.
- Tensor Flow is a library for large-scale machine learning and deep learning using data flow graphs. Nodes in the graph represent operations and edges represent multidimensional data arrays called tensors.
- It supports CPU and GPU processing on desktops, servers, and mobile devices. Models can be visualized using TensorBoard.
- An example shows how to build an image classifier using transfer learning with the Inception model. Images are retrained on flower categories to classify new images.
- Distributed Tensor Flow allows a graph to run across multiple machines in a cluster for greater performance.
Automatic License Plate Recognition using OpenCVEditor IJCATR
Automatic License Plate Recognition system is a real time embedded system which automatically recognizes the license plate of vehicles. There are many applications ranging from complex security systems to common areas and from parking admission to urban traffic control. Automatic license plate recognition (ALPR) has complex characteristics due to diverse effects such as of light and speed. Most of the ALPR systems are built using proprietary tools like Matlab. This paper presents an alternative method of implementing ALPR systems using Free Software including Python and the Open Computer Vision Library.
Automatic License Plate Recognition using OpenCV Editor IJCATR
Automatic License Plate Recognition system is a real time embedded system which automatically recognizes the license plate of vehicles. There are many applications ranging from complex security systems to common areas and from parking admission to urban traffic control. Automatic license plate recognition (ALPR) has complex characteristics due to diverse effects such as of light and speed. Most of the ALPR systems are built using proprietary tools like Matlab. This paper presents an alternative method of implementing ALPR systems using Free Software including Python and the Open Computer Vision Library.
Applications use in Java GUIThe Java GUI consists of a separate, .pdfakshay1213
Applications use in Java GUI:
The Java GUI consists of a separate, automous task execution thread called the \"event loop\".
Every action that affects the GUI, e.g. calls to repaint the screen or to manipulate the properties
of a GUI component, or is a result of something happening to the GUI, e.g. the user clicks the
mouse or hits a key, is encapsulated in the form of an \"event\" that is placed into a queue for the
event loop to process. The result of processing an event may be a manipulation of the bits of
color on the screen or it may result in calls to methods in the developer\'s code.
1.A Java GUI application uses the standard Java components GUI component set, Swing, and is
deployed to the desktop.
2.The Swing GUI Builder in NetBeans IDE simplifies the GUI development process and enables
you to visually create Java GUI applications using pre-installed Swing and AWT components.
3.JavaFX is a rich set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications (RIAs) that behave consistently across multiple
platforms.
Similariti Between JAVA and JAVA GUI:
I think in many cases the overhead incurred to run a JVM is acceptable because of the
functionality the code base
provides.So winding back a bit, the reason that functionality can exist with Java has much to do
with the language/environment which frees programmers from a lot of resource management and
allows them to focus
more on plugging together components. Time to market and all that jazz.Like a lot of interpreted
languages, Java\'s development cycle ispretty excellent I think. A programmer can get a fairly
complicatedapplication off the ground quickly due to a number of things broughtabout both by
the interp-language development paradigm that allows for
immediate detection of errors and compile-and-test-as-you-code sessions.I think those are the
kinds of things which has made Java popular.
Some Java applications that you can install and play with on your own desktop machine:
1.Eclipse
2.NetBeans
3.jEdit
4.OpenOffice
Java is used in
JAVA GUI:
The Java GUI system however is a legacy issue where the system underwent a large-scale
upgrade , so some of the classes involved are spread over the (relatively) older java.awt packages
and the newer javax.swing packages. In general, if the class name starts with \"J\", then it is in
the Swing package. Since some functionality appears to be duplicated in the Swing packages,
such as frames and buttons, always use the Swing component over the older AWT components
when there is a choice.
Commonly Used Methods in GUI Components:
void setPreferredSize(int width, int height) :sets the size of a component to be used when the
layout manager is able to use that size, e.g. there is enough room. Some layout managers always
ignore the size setting of a component because the size is under other constraints..
String getText(), void setText(String s) :accessor methods for the text of labels, button.
Implementation of embedded arm9 platform using qt and open cv for human upper...Krunal Patel
: In this Paper, A novel architecture for automotive vision using an embedded device will be
implemented on ARM9 Board with highly computing capabilities and low processing power. Currently,
achieving real-time image processing routines such as convolution, thresholding, edge detection and some of the
complex media applications is a challenging task in embedded Device, because of limited memory. An open
software framework, Linux OS is used in embedded devices to provide a good starting point for developing the
multitasking kernel, integrated with communication protocols, data management and graphical user interface for
reducing the total development time. To resolve the problems faced by the image processing applications in
embedded Device a new application environment was developed. This environment provides the resources
available in the operating system which runs on the hardware with complex image processing libraries. This
paper presents the capture of an image from the USB camera, applied to image processing algorithms to Detect
Human Upper Body. The application (GUI) Graphical User Interface was designed using Qt and ARM Linux
gcc Integrated Development Environment (IDE) for implementing image processing algorithm using Open
Source Computer Vision Library (OpenCV). This developed software integrated in mobiles by the cross
compilation of Qt and the OpenCV software for Linux Operating system. The result utilized by Viola and Jones
Algorithm with Haar Features of the image using OpenCV.
An API is a set of routines and protocols that allows software developers to build applications. It provides standard ways to develop applications that will work within an operating system. Popular 3D graphics APIs like OpenGL and Direct3D define standard pipelines that graphics hardware uses to process 3D scenes and convert them into 2D images for display. The graphics pipeline involves several stages including clipping, lighting, texturing, rasterization, and display.
This document discusses Java graphics and input/output. It introduces the Graphics class in Java AWT which is used to draw on components. It describes various Graphics methods like drawString, drawRect. It also discusses AWT event handling and different event classes. Finally, it covers Java I/O streams like InputStream, OutputStream and file streams like FileInputStream and FileOutputStream along with methods to read and write from files.
The document discusses visualization systems and proposes concepts for their future development. It summarizes:
1) The "Visual Realityware" visualization software development environment, which uses an abstraction layer to allow developers to freely select mainstream graphics technologies and expand applications across multiple platforms with minimal bugs.
2) An application called "Virtual Anatomia" developed using Visual Realityware to visualize 3D biological data in real-time.
3) The concept of "Visionize" which is defined as a risk management methodology using visual communication to allow sharing of goals and visions in order to identify and prevent risks before issues arise.
- Tensor Flow is a library for large-scale machine learning and deep learning using data flow graphs. Nodes in the graph represent operations and edges represent multidimensional data arrays called tensors.
- It supports CPU and GPU processing on desktops, servers, and mobile devices. Models can be visualized using TensorBoard.
- An example shows how to build an image classifier using transfer learning with the Inception model. Images are retrained on flower categories to classify new images.
- Distributed Tensor Flow allows a graph to run across multiple machines in a cluster for greater performance.
Automatic License Plate Recognition using OpenCVEditor IJCATR
Automatic License Plate Recognition system is a real time embedded system which automatically recognizes the license plate of vehicles. There are many applications ranging from complex security systems to common areas and from parking admission to urban traffic control. Automatic license plate recognition (ALPR) has complex characteristics due to diverse effects such as of light and speed. Most of the ALPR systems are built using proprietary tools like Matlab. This paper presents an alternative method of implementing ALPR systems using Free Software including Python and the Open Computer Vision Library.
Automatic License Plate Recognition using OpenCV Editor IJCATR
Automatic License Plate Recognition system is a real time embedded system which automatically recognizes the license plate of vehicles. There are many applications ranging from complex security systems to common areas and from parking admission to urban traffic control. Automatic license plate recognition (ALPR) has complex characteristics due to diverse effects such as of light and speed. Most of the ALPR systems are built using proprietary tools like Matlab. This paper presents an alternative method of implementing ALPR systems using Free Software including Python and the Open Computer Vision Library.
This document discusses computer graphics and graphics workstations. It provides details on:
- The capabilities of typical graphics workstations, including 2D/3D modeling, animation, color selection, 3D viewing, and other features.
- The architecture of graphics workstations, which typically include a RISC microprocessor, large memory and storage, and specialized graphics boards.
- Common display algorithms used in computer graphics like raster scan techniques, DDA and Bresenham's line drawing algorithms, which allow for fast rendering of basic shapes and lines on raster displays.
Do Not just learn computer graphics an close your computer tab and go away..
APPLY them in real business,
Visit Daroko blog for real IT skills applications,androind, Computer graphics,Networking,Programming,IT jobs Types, IT news and applications,blogging,Builing a website, IT companies and how you can form yours, Technology news and very many More IT related subject.
-simply google:Daroko blog(professionalbloggertricks.com)
• Daroko blog (www.professionalbloggertricks.com)
• Presentation by Daroko blog, to see More tutorials more than this one here, Daroko blog has all tutorials related with IT course, simply visit the site by simply Entering the phrase Daroko blog (www.professionalbloggertricks.com) to search engines such as Google or yahoo!, learn some Blogging, affiliate marketing ,and ways of making Money with the computer graphic Applications(it is useless to learn all these tutorials when you can apply them as a student you know),also learn where you can apply all IT skills in a real Business Environment after learning Graphics another computer realate courses.ly
• Be practically real, not just academic reader
1) The document describes a student project on creating a small animation using Java applets. It includes an introduction to Java applets and animation.
2) The code presented animates bouncing balls on the applet screen by changing their position and color over time using threads and random number generation.
3) The conclusion states that the animation of a bouncing ball moving on the screen was successfully developed and run on a local computer using various applet functions to draw graphics and movement.
The Java STEP Viewer is software that parses and displays 3D models from STEP files. It uses Java for platform independence and the Java3D API to render models using OpenGL or DirectX. The software follows a model-viewer-controller design where the controller parses the STEP file and creates model objects, the viewer handles rendering, and the model represents the 3D geometry. Future versions will add more interactivity with sub-assemblies.
This document outlines an assignment for a computer vision course. Students are asked to implement 4 vision algorithms: 2 using OpenCV and 2 using MATLAB. The algorithms are the log-polar transform, background subtraction, histogram equalization, and contrast stretching. Students must also answer 3 short questions about orthographic vs perspective projection, efficient filtering, and sensors beyond cameras for computer vision.
This document provides an overview of computer graphics concepts including:
- Definition and components of computer graphics
- SRGP (Simple Raster Graphics Package) for drawing shapes and handling basic interactions
- Raster graphics features like canvases, clipping, and copy pixel
- Limitations of SRGP
- Display technologies like raster scan displays, random scan displays, and video controllers
- Input devices for user interaction like locators, keyboards, and logical input/output
1. The document discusses migrating from OpenGL to Vulkan, providing analogies comparing the APIs to fixed-function toys, programmable LEGO kits, and raw materials pine wood derby kits.
2. It outlines scenarios that are likely and unlikely to benefit from Vulkan, such as applications with parallelizable CPU-bound graphics work.
3. Key differences between OpenGL and Vulkan are explained, such as Vulkan requiring explicit management of graphics resources, synchronization, and command buffer queuing. The document emphasizes that transitioning to Vulkan truly rethinks the entire graphics rendering approach.
The document discusses computer graphics and provides examples of its applications. It discusses graphics inbuilt functions such as arc(), initgraph(), closegraph(), and line(). It provides code snippets and explanations for these functions. It also lists algorithms for direct and Bresenham lines, circles, ellipses, and their code programs. Finally, it mentions static and dynamic applications of computer graphics.
A System For Building Animated Presentations Over The WebSara Alvarez
This document describes Leonardo Web, a system for creating animated presentations for teaching and learning. It has three main components: the Builder visual editor, the Player viewer, and the Library script generation library. The Builder allows creating presentations by assembling key frames containing graphical objects. The Player can display presentations as standalone applications or web applets, supporting step-by-step or continuous playback. The Library allows generating animation scripts programmatically from Java code to batch-produce visualizations. Presentations can combine script generation and visual editing for flexibility.
This document discusses drawing 2D and 3D graphics with OpenGL ES 1.x and 2.x APIs in Android NDK. It covers drawing 2D shapes and applying transforms using OpenGL ES 1.x, including translating, scaling and rotating shapes. It also discusses the graphics rendering pipeline in OpenGL and differences between the fixed pipeline in OpenGL ES 1.x versus the programmable pipeline in OpenGL ES 2.0. The document provides code samples for drawing 2D triangles and squares in Android NDK and applying common transforms.
This document discusses fundamentals of Java programming including why Java is an important language, how Java code is compiled and run, the structure of simple Java programs, and user interface styles. It provides examples of simple "Hello World" and temperature conversion programs, explaining key concepts like variables, objects, methods, and layout managers. The document is intended to help readers understand basic Java programming principles.
The document discusses different approaches to drawing graphics on a computer screen, including raster-based and vector-based graphics. It focuses on raster-based drawing APIs and their evolution from native platform-specific APIs to platform-independent APIs in web browsers. Key developments included the use of browser plugins, problems with plugins, and the introduction of HTML5 Canvas which enables interactive drawing in browsers without plugins.
This document contains information about computer graphics including:
1. An introduction to computer graphics, its applications, and basic functions like drawing lines, circles, rectangles.
2. Details of 4 assignments - the first involves studying graphics functions, the second develops a CPU architecture GUI, the third defines a point class, and the fourth defines line and circle drawing classes.
3. The last assignment involves writing C++ classes to draw lines using DDA and Bresenham's algorithms and inheriting from the point class, and a circle class inheriting from the line class.
A Java-Based System For Building Animated Presentations Over The WebScott Faria
This document describes Leonardo Web, a Java-based system for creating animated presentations that can be viewed over the web. It has three main components: The Builder is a visual editor for building and editing presentations. The Player is a viewer that can display presentations as a standalone app or web applet. The Library allows generating animations directly from Java code by inserting calls to graphical routines. Presentations can be created visually or programmatically and viewed online or offline through a simple player.
This report describes an approach of using a “Master-Slave” network communication mechanism by using Java Bindings for OpenGL API (Jogl), based on a real implementation, to achieve the effect of displaying 3D object within multiple screens.
This document provides an overview of topics to be covered in a mid-term exam for a computer graphics course. The topics include introductions and applications of computer graphics, graphics hardware and I/O devices, interactive and non-interactive computer graphics, raster and vector graphics, scan converting lines and shapes, 2D transformations, 2D viewing, and 2D zooming and panning. The document was prepared by Bahadar sher and provides his email for contact.
Design the implementation of Anytime D Star on an Occupancy GridAnkita Tiwari
This experiment aims to study and design the implementation of Anytime D Star path planning on an occupancy grid. The experiment uses LabVIEW to create a main VI that uses the Anytime D* search algorithm to calculate a suboptimal path quickly and then update the path in subsequent executions until an optimal path is found. Sub-VIs are used to generate random obstacles, check valid cells, convert paths to the grid, and reveal portions of the world. The results show that the VI can plan paths efficiently using information from previous iterations to handle changes in the robot's environment or goal.
This document discusses the history and evolution of graphical user interfaces (GUIs) in web browsers. It begins by explaining the concepts of vector-based and raster-based graphics. It then describes early approaches using bare HTML pages, which felt like navigation rather than a true application. Plugins were introduced to provide richer content but had problems with resources, installation, and security. Finally, the document introduces HTML5 Canvas as a solution for continuous, event-driven drawing without plugins, allowing single-page web applications.
Variables in a Research Study and Data CollectionIn this assignmen.docxdaniahendric
Variables in a Research Study and Data Collection
In this assignment, you will explore the variables involved in a research study.
Complete the following tasks:
Read the following articles from the Cumulative Index to Nursing and Allied Health Literature (CINAHL) Database in the South University Online Library.
Lee, A., Craft-Rosenberg, M. (2010). Ineffective family participation in
professional care: A concept analysis of a proposed nursing
diagnosis.
Nurs Diagn
. 2002 Jan-Mar;
13
(1), 5–14.
Witt, C. M., Lüdtke, R., Willich, S. N. (2010). Homeopathic treatment
of patients with migraine: A prospective observational study with
a 2-year follow-up period.
J Altern Complement Med
. 2010 Apr;
16
(4), 347–55. doi: 10.1089/acm.2009.0376.
Read the process for data collection employed in both these studies. Compare the method used in each of them.
Provide a bulleted list of the five tasks performed as part of data collection in each of them. Click
here
to enter your responses in the organizer.
.
Variation exists in virtually all parts of our lives. We often see v.docxdaniahendric
Variation exists in virtually all parts of our lives. We often see variation in results in what we spend (utility costs each month, food costs, business supplies, etc.). Consider the measures and data you use (in either your personal or job activities). When are differences (between one time period and another, between different production lines, etc.) between average or actual results important? How can you or your department decide whether or not the observed differences over time are important? How could using a mean difference test help?
.
More Related Content
Similar to An Introduction to Computer Science with Java .docx
This document discusses computer graphics and graphics workstations. It provides details on:
- The capabilities of typical graphics workstations, including 2D/3D modeling, animation, color selection, 3D viewing, and other features.
- The architecture of graphics workstations, which typically include a RISC microprocessor, large memory and storage, and specialized graphics boards.
- Common display algorithms used in computer graphics like raster scan techniques, DDA and Bresenham's line drawing algorithms, which allow for fast rendering of basic shapes and lines on raster displays.
Do Not just learn computer graphics an close your computer tab and go away..
APPLY them in real business,
Visit Daroko blog for real IT skills applications,androind, Computer graphics,Networking,Programming,IT jobs Types, IT news and applications,blogging,Builing a website, IT companies and how you can form yours, Technology news and very many More IT related subject.
-simply google:Daroko blog(professionalbloggertricks.com)
• Daroko blog (www.professionalbloggertricks.com)
• Presentation by Daroko blog, to see More tutorials more than this one here, Daroko blog has all tutorials related with IT course, simply visit the site by simply Entering the phrase Daroko blog (www.professionalbloggertricks.com) to search engines such as Google or yahoo!, learn some Blogging, affiliate marketing ,and ways of making Money with the computer graphic Applications(it is useless to learn all these tutorials when you can apply them as a student you know),also learn where you can apply all IT skills in a real Business Environment after learning Graphics another computer realate courses.ly
• Be practically real, not just academic reader
1) The document describes a student project on creating a small animation using Java applets. It includes an introduction to Java applets and animation.
2) The code presented animates bouncing balls on the applet screen by changing their position and color over time using threads and random number generation.
3) The conclusion states that the animation of a bouncing ball moving on the screen was successfully developed and run on a local computer using various applet functions to draw graphics and movement.
The Java STEP Viewer is software that parses and displays 3D models from STEP files. It uses Java for platform independence and the Java3D API to render models using OpenGL or DirectX. The software follows a model-viewer-controller design where the controller parses the STEP file and creates model objects, the viewer handles rendering, and the model represents the 3D geometry. Future versions will add more interactivity with sub-assemblies.
This document outlines an assignment for a computer vision course. Students are asked to implement 4 vision algorithms: 2 using OpenCV and 2 using MATLAB. The algorithms are the log-polar transform, background subtraction, histogram equalization, and contrast stretching. Students must also answer 3 short questions about orthographic vs perspective projection, efficient filtering, and sensors beyond cameras for computer vision.
This document provides an overview of computer graphics concepts including:
- Definition and components of computer graphics
- SRGP (Simple Raster Graphics Package) for drawing shapes and handling basic interactions
- Raster graphics features like canvases, clipping, and copy pixel
- Limitations of SRGP
- Display technologies like raster scan displays, random scan displays, and video controllers
- Input devices for user interaction like locators, keyboards, and logical input/output
1. The document discusses migrating from OpenGL to Vulkan, providing analogies comparing the APIs to fixed-function toys, programmable LEGO kits, and raw materials pine wood derby kits.
2. It outlines scenarios that are likely and unlikely to benefit from Vulkan, such as applications with parallelizable CPU-bound graphics work.
3. Key differences between OpenGL and Vulkan are explained, such as Vulkan requiring explicit management of graphics resources, synchronization, and command buffer queuing. The document emphasizes that transitioning to Vulkan truly rethinks the entire graphics rendering approach.
The document discusses computer graphics and provides examples of its applications. It discusses graphics inbuilt functions such as arc(), initgraph(), closegraph(), and line(). It provides code snippets and explanations for these functions. It also lists algorithms for direct and Bresenham lines, circles, ellipses, and their code programs. Finally, it mentions static and dynamic applications of computer graphics.
A System For Building Animated Presentations Over The WebSara Alvarez
This document describes Leonardo Web, a system for creating animated presentations for teaching and learning. It has three main components: the Builder visual editor, the Player viewer, and the Library script generation library. The Builder allows creating presentations by assembling key frames containing graphical objects. The Player can display presentations as standalone applications or web applets, supporting step-by-step or continuous playback. The Library allows generating animation scripts programmatically from Java code to batch-produce visualizations. Presentations can combine script generation and visual editing for flexibility.
This document discusses drawing 2D and 3D graphics with OpenGL ES 1.x and 2.x APIs in Android NDK. It covers drawing 2D shapes and applying transforms using OpenGL ES 1.x, including translating, scaling and rotating shapes. It also discusses the graphics rendering pipeline in OpenGL and differences between the fixed pipeline in OpenGL ES 1.x versus the programmable pipeline in OpenGL ES 2.0. The document provides code samples for drawing 2D triangles and squares in Android NDK and applying common transforms.
This document discusses fundamentals of Java programming including why Java is an important language, how Java code is compiled and run, the structure of simple Java programs, and user interface styles. It provides examples of simple "Hello World" and temperature conversion programs, explaining key concepts like variables, objects, methods, and layout managers. The document is intended to help readers understand basic Java programming principles.
The document discusses different approaches to drawing graphics on a computer screen, including raster-based and vector-based graphics. It focuses on raster-based drawing APIs and their evolution from native platform-specific APIs to platform-independent APIs in web browsers. Key developments included the use of browser plugins, problems with plugins, and the introduction of HTML5 Canvas which enables interactive drawing in browsers without plugins.
This document contains information about computer graphics including:
1. An introduction to computer graphics, its applications, and basic functions like drawing lines, circles, rectangles.
2. Details of 4 assignments - the first involves studying graphics functions, the second develops a CPU architecture GUI, the third defines a point class, and the fourth defines line and circle drawing classes.
3. The last assignment involves writing C++ classes to draw lines using DDA and Bresenham's algorithms and inheriting from the point class, and a circle class inheriting from the line class.
A Java-Based System For Building Animated Presentations Over The WebScott Faria
This document describes Leonardo Web, a Java-based system for creating animated presentations that can be viewed over the web. It has three main components: The Builder is a visual editor for building and editing presentations. The Player is a viewer that can display presentations as a standalone app or web applet. The Library allows generating animations directly from Java code by inserting calls to graphical routines. Presentations can be created visually or programmatically and viewed online or offline through a simple player.
This report describes an approach of using a “Master-Slave” network communication mechanism by using Java Bindings for OpenGL API (Jogl), based on a real implementation, to achieve the effect of displaying 3D object within multiple screens.
This document provides an overview of topics to be covered in a mid-term exam for a computer graphics course. The topics include introductions and applications of computer graphics, graphics hardware and I/O devices, interactive and non-interactive computer graphics, raster and vector graphics, scan converting lines and shapes, 2D transformations, 2D viewing, and 2D zooming and panning. The document was prepared by Bahadar sher and provides his email for contact.
Design the implementation of Anytime D Star on an Occupancy GridAnkita Tiwari
This experiment aims to study and design the implementation of Anytime D Star path planning on an occupancy grid. The experiment uses LabVIEW to create a main VI that uses the Anytime D* search algorithm to calculate a suboptimal path quickly and then update the path in subsequent executions until an optimal path is found. Sub-VIs are used to generate random obstacles, check valid cells, convert paths to the grid, and reveal portions of the world. The results show that the VI can plan paths efficiently using information from previous iterations to handle changes in the robot's environment or goal.
This document discusses the history and evolution of graphical user interfaces (GUIs) in web browsers. It begins by explaining the concepts of vector-based and raster-based graphics. It then describes early approaches using bare HTML pages, which felt like navigation rather than a true application. Plugins were introduced to provide richer content but had problems with resources, installation, and security. Finally, the document introduces HTML5 Canvas as a solution for continuous, event-driven drawing without plugins, allowing single-page web applications.
Similar to An Introduction to Computer Science with Java .docx (20)
Variables in a Research Study and Data CollectionIn this assignmen.docxdaniahendric
Variables in a Research Study and Data Collection
In this assignment, you will explore the variables involved in a research study.
Complete the following tasks:
Read the following articles from the Cumulative Index to Nursing and Allied Health Literature (CINAHL) Database in the South University Online Library.
Lee, A., Craft-Rosenberg, M. (2010). Ineffective family participation in
professional care: A concept analysis of a proposed nursing
diagnosis.
Nurs Diagn
. 2002 Jan-Mar;
13
(1), 5–14.
Witt, C. M., Lüdtke, R., Willich, S. N. (2010). Homeopathic treatment
of patients with migraine: A prospective observational study with
a 2-year follow-up period.
J Altern Complement Med
. 2010 Apr;
16
(4), 347–55. doi: 10.1089/acm.2009.0376.
Read the process for data collection employed in both these studies. Compare the method used in each of them.
Provide a bulleted list of the five tasks performed as part of data collection in each of them. Click
here
to enter your responses in the organizer.
.
Variation exists in virtually all parts of our lives. We often see v.docxdaniahendric
Variation exists in virtually all parts of our lives. We often see variation in results in what we spend (utility costs each month, food costs, business supplies, etc.). Consider the measures and data you use (in either your personal or job activities). When are differences (between one time period and another, between different production lines, etc.) between average or actual results important? How can you or your department decide whether or not the observed differences over time are important? How could using a mean difference test help?
.
Valerie Matsumoto's "Desperately Seeking "Deirde": Gender Roles, Multicultural Relations, and Nisei Women Writers of the 1930s," focuses on the writings of Deirde, a second generation Japanese American advice columnist. But as the abstract of this piece suggests, Matsumoto was not so much interested in the advice Deirde was giving her readers as much as she was interested in the questions her readers were asking the "Dear Abby"of their community in the mid-1930s to early 1940s. What were they asking about? From Deidre's columns, what were some of the concerns of the Japanese-American community during 1935-1941? While it is of extreme importance to study the experience of the Japanese-Americans during World War II , Matsumoto argues that it is also of importance to study the pre-war lives of Japanese-Americans. Why? What did these concerns reveal about the Japanese-American experience in the United States during this time period?
.
valerie is a 15 year old girl who has recently had signs of a high f.docxdaniahendric
valerie is a 15 year old girl who has recently had signs of a high fever, her parents took her to the ER and the test results say she has a bacterial infection and her white blood cells are trapping bacteria it is not binding with the vacuole and releasing necessarg enzymes to break the cell wall. What disease does valerie have?
.
Utilizing the Statement of Financial Position on page 196 of the Acc.docxdaniahendric
Utilizing the Statement of Financial Position on page 196 of the Accounting Fundamentals for Health Care Management text book (see attachement), compare the figures for 2013 and 2012. Compose a narrative of possible explanations for the documented charges in the year-end figures for the organization. Your response should be a minimum of 200 words in length and submitted in a Word document, utilizing APA format.
See attachment referencing Statement of Financial Position
.
Utech Company has income before irregular items of $307,500 for the .docxdaniahendric
Utech Company has income before irregular items of $307,500 for the year ended December 31, 2014. It also has the following items (before considering income taxes): (1) an extraordinary fire loss of $53,000 and (2) a gain of $27,100 from the disposal of a division. Assume all items are subject to income taxes at a 39% tax rate.
Prepare Utech Company’s income statement for 2014, beginning with “Income before irregular items.”
.
Using your work experience in the public and nonprofit sector, and t.docxdaniahendric
Using your work experience in the public and nonprofit sector, and the knowledge you have gained in this MPA program as a guide, address the following question in a detailed fashion:
What methods, specifically, have citizens utilized to influence and become involved in the budgeting and financial management arenas in the public sphere? Which movements or strategies have been most successful from a citizen perspective? To what degree do budgeting professionals and public administrators seek and consider this citizen involvement? What will be the trend for the future with regard to citizen participation in the process?
.
Using your textbook, provide a detailed and specific definition to.docxdaniahendric
Using your textbook, provide a detailed and specific definition to the following terms:
Transformation Leadership
Transactional Leadership
Laissez-Faire Leadership
Idealized Influence
Inspirational Motivation
Intellectual Stimulation
Idealized Consideration
Contingent Reward
Management by Exception
Kouzes and Posner wrote a book entitled the
Leadership Challenge
in which they identified five practices of exemplary leaders. Using your textbook and Internet sources, discuss the five practices and give examples of leadership behaviors that would illustrate the practice. (1 page minimum)
.
Using your text and at least one scholarly source, prepare a two to .docxdaniahendric
Using your text and at least one scholarly source, prepare a two to three page paper (excluding title and reference page), in APA format, on the following:
Explain the difference between Charity Care and Bad Debt in a healthcare environment.
Explain how the patient financial services personnel assist in determining which category the uncollectible account should be placed.
Discuss the financial implications of gross uncollectibles on the bottom line of the healthcare institution, and explain how these are recorded on the financial statements.
This is the textbook that we are on:
Epstein, L. & Schneider, A. (2014).
Accounting for Health Care Professionals
. San Diego, CA: Bridgepoint Education, Inc.
.
Using Walgreen Company as the target organization complete the.docxdaniahendric
Using
Walgreen Company
as the target organization complete the following three-step process:
First, conduct an external assessment and complete either an EFE or CPM. Use the following five websites in conducting your assessment:
http://marketwatch.com
www.hoovers.com
http://moneycentral.msn.com
http://us.etrade.com/e/t/invest/markets
http://globaledge.msu.edu/industries
Second, conduct an internal assessment and complete an IFE. Use the following documents, which may be found in the target organization’s corporate website:
Most current Form10K document
Most current Annual Report
Then develop a well-written paper describing the findings that you discovered by
analyzing the data
from the external assessment and from the internal assessment.
Present facts.
Consider putting some of the data into a graphical display (chart, figure, table) to present information in a clear way. Use citations to substantiate your ideas. Insert the completed matrixes as appendixes and reference them within the body of the paper according to APA standards.
Your paper should meet the following requirements:
Be 2-3 pages in length
Be formatted according to
APA GUIDELINES
Cite a minimum of three outside sources.
Include all required elements, including a reference page and required appendixes.
.
Using the text book and power point on Interest Groups, please ans.docxdaniahendric
Interest groups use various tactics to influence political parties and policymakers, including lobbying. There are different types of interest groups, with some being more powerful in certain states than others. Lobbyists represent interest groups and try to sway legislators through various approved methods outlined in the attached powerpoint presentation.
Using the template provided in attachment create your own layout.R.docxdaniahendric
Using the template provided in attachment create your own layout.
Review the Goals
Who is the Persona you are trying to reach?
Use the "How to Change Consumer Behavior" file
Integrate social media
A Twitter feed needs to be on the Home Page
Use a Site Architecture Excel File to let the IT Developer know sub menus
Simplify wherever you can. What is the 1 message you want the viewer to remember?
.
Using the simplified OOD methodologyWrite down a detailed descrip.docxdaniahendric
The document provides instructions for using the simplified Object-Oriented Design (OOD) methodology to design software for a police department. The methodology involves writing a description of the problem, identifying relevant nouns and verbs, selecting objects from the nouns and their data components, selecting operations from the verbs, and writing a paper proposing classes with data members and methods for tracking people, property, and criminal activity.
Using the text, Cognitive Psychology 5 edition (Galotti, 2014), .docxdaniahendric
Using the text,
Cognitive Psychology 5 edition
(Galotti, 2014), the University Library, the Internet, and/or other resources, answer the following questions. Your response to each question should be at least 150 words in length.
1.
What is primary memory? What are the characteristics of primary memory?
2.
What is the process of memory from perception to retrieval? What happens when the process is compromised?
3.Is it possible for memory retrieval to be unreliable? Why or why not? What factors may affect the reliability of one’s memory?
.
Using the Tana Basin in Kenya,1.Discuss the water sources and .docxdaniahendric
Using the Tana Basin in Kenya,
1.
Discuss the water sources and their quality - ( 5 marks)
2.
Outline the factors that influence their potential uses - (5 marks)
3.
Identify and map the current users of water in the catchment - (15 marks)
4.
Map the potential source of pollution in the catchment - (5 marks)
Need three pages APA format.
.
Using the template provided in a separate file, create your own la.docxdaniahendric
Using the template provided in a separate file, create your own layout.
Review the Goals
Who is the Persona you are trying to reach?
Use the "How to Change Consumer Behavior" file
Integrate social media
A Twitter feed needs to be on the Home Page
Use a Site Architecture Excel File to let the IT Developer know sub menus
Simplify wherever you can. What is the 1 message you want the viewer to remember?
.
Using the template provided in attachment create your own layo.docxdaniahendric
The document provides instructions for creating a website layout using the provided template, reviewing goals, identifying the target persona, integrating information from an attached file on changing consumer behavior, including a Twitter feed on the home page, using an Excel file to communicate the site architecture and submenus to developers, and simplifying the design to focus on one key message for viewers.
Using the Sex(abled) video, the sexuality section in the Falvo text.docxdaniahendric
Using the "Sex(abled) video, the sexuality section in the Falvo text (Chapter 12), and your own thoughts and experiences as context, describe prominent issues related to forming intimate relationships by people with intellectual disabilities. You may consider the viewpoints from caregivers and family members, educators, societal attitudes, counselors or support personnel, and viewpoints from people with disabilities. You may include disabilities outside of intellectual disabilities if you wish.
Watch Video: Sexuality and Relationships
.
Using the required and recommended resources from this week and last.docxdaniahendric
Using the required and recommended resources from this week and last, as well as ‘found’ resources, identify at least one specific example of groups or individuals in your community, state, or at the national level that exemplify the following themes and include a brief description of why you feel this example meets the concept. Add a link for any ‘found’ resources.
Works “with” young people rather than conducting activities “for” them.
Creates an atmosphere that sparks young people’s aspirations.
Digs deep and incorporates key elements of authentic youth involvement by making sure that:
Youth are valued and heard
Youth shape the action agenda
Youth build assets for and with each other
Why is it important for programs and or organizations to work “with” young people rather than “for” them?
.
Using the Internet, textbook or related resources, research the crea.docxdaniahendric
Using the Internet, textbook or related resources, research the creation and role of the Federal Reserve. Then in a 1-2 page paper, address the following:
When was the Federal Reserve created and for what purpose?
How does the Federal Reserve manipulate our economy to foster economic growth?
Research at
least three
specific policies instituted by the Federal Reserve.
Finally give an analysis as to why or why not you feel these policies were successful. Remember to support your position with cited sources
Due Sunday 11/30/14 at 11am CST, in APA format with APA bibliography
.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxEduSkills OECD
Iván Bornacelly, Policy Analyst at the OECD Centre for Skills, OECD, presents at the webinar 'Tackling job market gaps with a skills-first approach' on 12 June 2024
Walmart Business+ and Spark Good for Nonprofits.pdfTechSoup
"Learn about all the ways Walmart supports nonprofit organizations.
You will hear from Liz Willett, the Head of Nonprofits, and hear about what Walmart is doing to help nonprofits, including Walmart Business and Spark Good. Walmart Business+ is a new offer for nonprofits that offers discounts and also streamlines nonprofits order and expense tracking, saving time and money.
The webinar may also give some examples on how nonprofits can best leverage Walmart Business+.
The event will cover the following::
Walmart Business + (https://business.walmart.com/plus) is a new shopping experience for nonprofits, schools, and local business customers that connects an exclusive online shopping experience to stores. Benefits include free delivery and shipping, a 'Spend Analytics” feature, special discounts, deals and tax-exempt shopping.
Special TechSoup offer for a free 180 days membership, and up to $150 in discounts on eligible orders.
Spark Good (walmart.com/sparkgood) is a charitable platform that enables nonprofits to receive donations directly from customers and associates.
Answers about how you can do more with Walmart!"
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
Reimagining Your Library Space: How to Increase the Vibes in Your Library No ...Diana Rendina
Librarians are leading the way in creating future-ready citizens – now we need to update our spaces to match. In this session, attendees will get inspiration for transforming their library spaces. You’ll learn how to survey students and patrons, create a focus group, and use design thinking to brainstorm ideas for your space. We’ll discuss budget friendly ways to change your space as well as how to find funding. No matter where you’re at, you’ll find ideas for reimagining your space in this session.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
How to Setup Warehouse & Location in Odoo 17 InventoryCeline George
In this slide, we'll explore how to set up warehouses and locations in Odoo 17 Inventory. This will help us manage our stock effectively, track inventory levels, and streamline warehouse operations.
How to Make a Field Mandatory in Odoo 17Celine George
In Odoo, making a field required can be done through both Python code and XML views. When you set the required attribute to True in Python code, it makes the field required across all views where it's used. Conversely, when you set the required attribute in XML views, it makes the field required only in the context of that particular view.
An Introduction to Computer Science with Java .docx
1. An Introduction to
Computer Science with Java
Copyright 2013 by C. Herbert, all rights reserved.
Last edited August 21, 2013 by C. Herbert
This document is a draft of a chapter from Computer Science
with Java, written by Charles Herbert with the assistance of
Craig
Nelson. It is available free of charge for students in Computer
Science 111 at Community College of Philadelphia during the
Fall
2013 semester. It may not be reproduced or distributed for any
other purposes without proper prior permission.
CSCI 111 Chapter 11 Graphics pg. 2
Introduction to
2. Computer Science with Java
Chapter 11 – Java Graphics
This short chapter describes how programmers can create and
manipulate two-dimensional graphics in
Java. It includes creating.
Chapter Learning Outcomes
Upon completion of this chapter students should be able to:
) is and why
GPUs are used
with modern computers.
classes are and
how they are used.
Graphics class:
o setting the Color for graphics;
o drawing lines;
o drawing rectangles, and rectangles with rounded corners;
o drawing ovals, circles, and arc of ovals and circles;
o drawing polygons;
o drawing text on the screen.
and scientific data.
3. figurative and abstract images.
11.1 Overview of Graphics Programming in Java
Graphics programming in Java is done through the use of APIs,
including the java.awt.Graphics class and
the Java 2D API that are both part of AWT; Java OpenGL
(JOGL), Java 3D (J3D), and Java Advanced
Imaging (JAI), which are official Java APIs; and many third
party APIs, such as the Java LightWeight
Game Library (JLWGL). The graphics capabilities in the AWT
and the Java OpenGL graphics libraries are
by far the most commonly used.
In this chapter we will focus on creating simple graphics and
concepts of graphics programming using
the graphics classes included in AWT, which will allow us to
create and manipulate simple graphic
images that can be displayed using the same containers as those
used for Swing components.
The graphics capabilities in AWT should work equally as well
on Windows, Mac and Linux-based
systems, although specialized coding for certain devices and
unique hardware configurations may
require the use of specialized APIs.
4. CSCI 111 Chapter 11 Graphics pg. 3
Generally, instructions in Java, as in any programming language
are fed through the operating system to
the computer’s hardware. In the case of graphics programming,
an additional component is often
present – a graphics processing unit. A graphics processing unit
(GPU), often called a graphics
accelerator, is a specialized processing unit for rendering high
quality images and video on a computer
screen. GPUs are often accompanied by additional specialized
graphics memory on a board that can be
added to a computer. Such boards are known as graphics cards.
GPU’s are used because of the massive amount of data involved
in imaging, especially video. A typical
HD television image has between 900.000 and 2.1 million pixels
per frame, with 3 or 4 bytes needed to
store each pixel. At 30 frames per second, the highest quality
raw video data would need a bandwidth in
the neighborhood of 30 billion bytes per second. Many special
techniques are used to reduce and
compress this data. The Society of Motion Picture and
Television Engineers (SMPTE ) has developed the
5. HD-SDI standard for broadcast HD video, which requires a
bandwidth of 1.485 Gbits/Sec.
The image below shows a modern ATI Raedon HD GPU, which
communicates with the CPU and 2 Gb of
graphics memory, and can control several display monitors. Its
components function as follows:
GPU for 3D video graphics and
can also perform 2D graphics.
still images.
U.
with the graphics memory.
communication between the memory
and the video processing engine.
units are proprietary circuits that
manipulate images moving from
6. video memory to the screen.
pipelines that translate graphic
images to coordinate system for the
hardware. They allow for parallel
processing of data moving to display
screens.
Even still images can require a lot of memory and processing
power. A 3-megapixel image from a
cellphone camera can use a megabyte of memory – which is as
much as 8 minutes of MP3 quality sound
or 64 thousand characters of Unicode text, roughly a 50 page
document.
CSCI 111 Chapter 11 Graphics pg. 4
11.2 Using the java.awt.Canvas and java.awt.Graphics Classes
The most commonly used classes for graphics programming in
Java are those found in AWT. They are
often used in conjunction with Swing components in GUI
programming. We will use two of those
7. classes: the java.awt.Canvas class and the java.awt.Graphics
class.
The Graphics class draws shapes on top of existing GUI
components, such as drawing an image on a
button. A Canvas class object in Java is a component
representing a blank window on which we may
draw shapes. We can also read user input on a Canvas, such as
the location of the screen pointer when
someone clicks a mouse button.
The paint() method is the method that draws on a component,
but the paint() method in the Canvas
class leaves the Canvas blank. We can create our own
customized Canvas as a subclass of the Canvas
class, then draw on our Canvas object by defining the
paint()method for our class.
Inside the paint() method we will use methods from the
java.awt.Graphics class to draw on our Canvas.
The java.awt.Graphics class contains many features for drawing
images. Quoting from Oracle’s Java
Tutorials Website
1
: “The Java 2D™ API is powerful and complex. However, the
vast majority of uses for
the Java 2D API utilize a small subset of its capabilities
8. encapsulated in the java.awt.Graphics class”.
Here is an example of how this works. The following code
creates a sub class of Canvas called MyCanvas,
with three simple rectangles. The paint() method in the
MyCanvas class will draw three rectangles on
the canvas, the second of which is a filled rectangle. The
objects are drawn in the order on which the
code to do so appears in method, so the second rectangle is on
top of the first, and the third in on top of
the second. The main() method creates and displays a JFrame
object containing a MyCanvas object.
/* ThreeRectangles.java
* last edited Nov. 15, 2013 by C.Herbert
*
* This code demonstrates the creation of a canvas subclass for
drawing
* by overriding the paint method() in the subclass.
*
* The main() method displays the canvas with our graphihcs in
a JFrame.
*
*
9. */
package threerectangles;
import java.awt.*;
import javax.swing.*;
public class ThreeRectangles {
public static void main(String[] args)
{
// create a MyCanvas object
1
The java graphics tutorials are available online at:
http://docs.oracle.com/javase/tutorial/2d/basic2d/index.html
They are
useful, but may be difficult to use for beginning programmers.
http://docs.oracle.com/javase/tutorial/2d/basic2d/index.html
CSCI 111 Chapter 11 Graphics pg. 5
MyCanvas canvas1 = new MyCanvas();
10. // set up a JFrame tpo hold the canvas
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setLocation(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the canvas to the frame as a content panel
frame.getContentPane().add(canvas1);
frame.setVisible(true);
} // end main()
} // end class ThreeRectangles
class MyCanvas extends Canvas
{
public MyCanvas()
{
11. } // end MyCanvas() constructor
public void paint(Graphics graphics)
// note: the graphics parameter is required as an artifact from
inheritance
{
graphics.setColor(Color.red);
graphics.drawRect(10, 10, 110, 110);
graphics.setColor(Color.green);
graphics.fillRect(35, 35, 135, 135);
graphics.setColor(Color.blue);
graphics.drawRect(60, 60, 160, 160);
} // end paint()
} // end class MyCanvas
In summary, methods from the Graphics class
(java.awt.Graphics) such as the drawRect() method, can
be used to draw on a GUI component. The Canvas class
(java.awt.Canvas) is a component that creates a
12. blank canvas just for such drawing. The paint method() in the
Canvas class leaves the canvas blank. We
can create our own canvas as a sub-class of the Canvas class
and draw on the canvas by overriding the
paint() method. The canvas can then be displayed by placing in
a container, such as a JFrame object, and
making the container visible.
11.3 Using Methods from the Graphics Class
In this section we will see how to draw with some of the most
commonly used methods from the
Graphics class, including methods for:
the Color for graphics;
CSCI 111 Chapter 11 Graphics pg. 6
We will start by looking at the coordinate system for onscreen
13. graphics.
Onscreen Coordinates
Most computer screens use an inverted Cartesian coordinate
system A Cartesian coordinate system –
named for its inventor René Descartes – is a standard two-
dimensional rectangular coordinate system
with an x values that increase to the right and y values that
increase upward. The two-dimensional
system is bisected horizontally by a vertical y-axis where x =0
and a horizontal x-axis where y=0, as
shown below. Points are located with an ordered pair of x and y
coordinates – (x,y).
CSCI 111 Chapter 11 Graphics pg. 7
An inverted Cartesian coordinate system is the same as a
14. Cartesian coordinate system, except that the
Y-axis values increase with movement downward. The first
computer screens that appeared in the
middle of the Twentieth Century displayed text in lines across
the screen with one line below another
starting from the top left corner of the screen. The text
coordinates were measured from the top left
corner across and down.
Graphics on computer monitors followed this convention, with
the origin in the top left corner of the
screen, the x-coordinate increasing across the screen from left
to right, and the y-coordinate increasing
down the screen from top to bottom. Thus the name inverted
Cartesian coordinate system, in which the
y coordinate goes up as we move down the screen.
In containers such as JFrames, the same inverted Cartesian
coordinate system is used. Points are
referenced by (x,y) ordered pairs, with the origin in the top
right corner of the frame. The x coordinate
increase to the right and the y coordinate increase downward.
The following sections describe some of the most commonly
used methods from the Graphics class. The
methods would be used in the paint method to draw on a
15. component, such as a class that extends the
Canvas class, as in the example on pages 4 and 5 above.
In these examples, instance is the name of the instance of the
graphics class. All coordinates are integer
values of data type int.
Drawing Lines
drawLine(int x1, int y1, int x2, int y2);
draws a line between the points (x1, y1)
and (x2, y2).
Drawing Rectangles
drawRect(int x, int y, int width, int height) draws the outline of
a rectangle of the specified width and
height with the top left corner at point (x,y). The bottom right
corner will be at point(x+width, y+height.
To draw a square, specify equal values for width and height.
fillRect(int x, int y, int width, int height) draws a filled
rectangle.
CSCI 111 Chapter 11 Graphics pg. 8
16. Rectangles with Rounded Corners
drawRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight) draws an outline of
rectangle with rounded-corners. The arcWidth and arcHeight
parameters set the horizontal and vertical
diameter of the arc used for the corners of the rectangle.
fillRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight) draws a filled rectangle.
The example below shows a standard rectangle and three
rectangles with rounded corners, each drawn
with different parameters.
Drawing Ovals and Circles
drawOval(int x, int y, int width, int height) draws an outline of
an oval within a rectangular area whose
top left corner is at point (x, y) and whose bottom right corner
is at point (x+width, y+height).
To draw a circle, specify equal values for width and height.
The diameter of the circle will be equal to
the value used for width and height; the radius will be half that
value. The center point of an oval or a
circle will be at coordinates (x+(width/2), y+(height/2)).
17. fillOval(int x, int y, int width, int height) draws a filled oval.
The example below shows three ovals, each drawn with
different parameters.
CSCI 111 Chapter 11 Graphics pg. 9
Drawing Arcs of Ovals and Circles
drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle) draws an outline of arc, which is
a segment of the perimeter of an oval where:
whose top left corner is at point (x, y)
and whose bottom right corner is at point (x+width, y+height);
extends for arcAngle degrees;
and measurement moves
18. counterclockwise around the oval for 360 degrees, as shown in
the diagram below.
fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle) draws a filled segment of an oval
defined by the specified arc.
The code below draws the arcs shown, each drawn with
different parameters.
CSCI 111 Chapter 11 Graphics pg. 10
Drawing Polygons
drawPolygon(int[] xPoints, int[] yPoints, int n) draws a polygon
with n vertex points defined by an array
of x coordinates, and an array y coordinates.
fillPolygon(int[] xPoints, int[] yPoints, int nPoints) draws a
filled polygon.
Drawing Text
drawString(String str, int x, int y) draws text specified by given
String, starting with the baseline of the
leftmost character at point (x,y).
19. The Color and Font of the text can be specified using the
setColor()and SetFont() methods for
components, as discussed in chapter 7, section 7.9.
The example below shows code to draw a text message
identifying a previously drawn shape.
CSCI 111 Chapter 11 Graphics pg. 11
Drawing Images from a Data File
drawImage(Image img, int x, int y, ImageObserver observer)
draws the image img with its top left
corner at the point (x,y). observer can be left null. Two lines
are required to create an image from a file
and display the image:
Image name = new ImageIcon( “filename” ).getImage();
instance.drawImage(name, x, y,null);
The first line will create an image with the name name from the
file identified by the String “filename”,
where “filename” may be a local or full context name of an
image file. The second line will draw the
20. image on the screen. This technique works with JPEG, PNG,
GIF, BMP and WBMP file types, although
there may be some timing issues loading animated GIF files as
Java Image class objects.
The following shows an example of this:
11.4 Programming Examples – a Histogram
A histogram is a graphic representation of data, also known as a
bar chart. In this example we will look
at a histogram created using java’s graphics class.
The first step in drawing any graphic image is to design the
image. We wish to create a bar chart
showing enrollments in Computer Science courses at
Community College of Philadelphia in the Fall
semester for four years. Here is the data:
year students
2010 ................. 106
2011 ................. 105
2012 ................. 142
2013 ................. 324
21. Sections were added in 2012 and again in 2013, increasing
enrollment.
A sample Netbeans project named DrawDemo that demonstrates
the commands in
this section is included in the files for this chapter.
CSCI 111 Chapter 11 Graphics pg. 12
We wish to create a histogram that looks something like this
one, created in Microsoft Excel:
We need to create text labels, rectangles to represent the data,
and the lines on the chart. The size of
each rectangle is related to the magnitude of the data. The
maximum data value is 324. We will use a
slightly higher number, 350, for the scale on our graph – 0 to
350. Each of our bars will be proportional
in size to 350.
year students
2010 ................. 106 106/350 = .303
2011 ................. 105 105/350 = .300
2012 ................. 142 142/350 = .406
22. 2013 ................. 324 324/350 = .926
Our scale for the graph will be 20 pixels for each 50 units of
data. This means that 350 units on the y-
axis will take up 140 pixels. They will be drawn up from the
bottom, with a baseline of y = 200.
The bars will be 20 pixels wide, with 20 pixels between bars.
We will also put a small picture of the Computer Science logo
in the upper left corner of the window.
The program needs to do the following:
1. place logo in corner
2. place title at top of chart
3. in a loop, place the horizontal lines and the labels for the
lines 50, 100, 150, etc. up to 350.
4. in a loop, draw the bars – every 40 units in the x direction, 20
units wide, with the height of the
filled rectangle for the bar determined by the enrollment value
for that bar.
CSCI 111 Chapter 11 Graphics pg. 13
The program has some math to calculate where things should be
drawn on the canvas, and to adjust
23. how the labels line up with lines and bars on the chart.
Here is what the finished histogram looks like:
The lines, labels and filled rectangles for the bars are each
drawn using standard Graphics class
statements. The difficult part is laying the design of the chart,
then doing a bit of tedious math to figure
out the coordinates for drawing the objects. The inverted
Cartesian screen coordinates make things a
bit more tedious. Using loops to draw the lines and the bars
saves some work.
The code to draw this histogram is included in the NetBeans
project Histogram, included with the files
for this chapter. Obviously, it is easier to use software such as
Excel to draw charts and graphs. This
project is included as an object of study to learn more about
using Graphics class objects in Java.
11.5 Programming Example – a Pie Chart
A pie chart, like the one shown below, depicts how each number
in a set of numbers is part of the whole
in proportion to the other parts. Pie charts can be created in
Java by using the fillArc()method.
Adjacent filled arcs are drawn for each value with the length of
the arc proportional to the size of the
24. value for that arc.
For a pie chart, we need to know where each arc starts and the
size of the arc in degrees. The total pie
chart will be 360 degrees. First we calculate the sum of the
values. Then, The size of the arc (in degrees)
that corresponds to each value will be (value* 360/sum). The
first arc will start at zero degrees. For each
slice of the pie chart, we will calculate the size of the arc, draw
the arc, then use the size to calculate the
starting angle for the next arc.
CSCI 111 Chapter 11 Graphics pg. 14
Each slice of the pie chart will have a value, a label for that
value, and a color. The label and value can
be read in from a data file or entered by a user. The colors can
be defined in the program.
We will also need a title for our pie chart. In the example
below, we will read data from a file that has:
the title of the chart on the first line, then sets of lines – each
having a line with a label, followed by a
line with the value that matches the label.
25. In addition to drawing the pie chart, we will draw a legend that
has a square with the same color as the
slice, along with the label and value for that color.
The following algorithm shows how to do this:
1. read the data file:
a. first, read the title
b. then in a loop,
c. Load the labels and values for each slice into arrays. We will
put the labels in the array
sliceLabel[]. We will put the values in the array sliceValue[].
Alternatively, this could be
done by letting the user enter the data.
d. As we load the values, we will also calculate the sum of the
values.
2. We will also need a color for each slice. We will call the
array sliceColor[].We can hardcode these
colors into our program. Color[] sliceColor = { Color.RED,
Color.BLUE, Color.GREEN,
Color.MAGENTA, Color. PINK, Color. GRAY, Color. CYAN,
Color. ORANGE} This array of colors can
handle up to 8 slices in the pie chart. Alternatively, we could
define our own Color for any slice,
26. by using a Color constructor with RGB values, such as new
Color(128,0, 255).
3. Draw the Title for the chart.
4. Draw the body of the chart. We need to keep track of where
each arc starts and the size of the
arc in degrees. We will initialize the starting angle to be 0
degrees. The total pie chart will be
CSCI 111 Chapter 11 Graphics pg. 15
360 degrees. The size of the arc (in degrees) corresponding to
each value will be
(sliceValue [i] * 360/sum). In a for loop for the number of
slices:
a. Calculate the size of the arc: (size = (a[i] * 360/sum) *
360)
b. Set the color for arc i to be sliceColor[i].
c. Draw the arc: fillArc(x, y, width, height, start, size)
d. Draw the square in the legend for this slice.
e. Add the label and value next to the square.
f. Calculate the value of start for the next slice: start = start +
size.
When the loop is finished, the chart will be done.
27. The code for this is included as the NetBeans project PieChart
in the files for this chapter. It draws the
pie chart above, showing the popular vote for the Dubious
Presidential Election of 1824, which resulted
in the House of Representatives selecting the president in what
has come to be known as the “Corrupt
Bargain”. You can draw pie charts for different data simply by
editing the PieChartData.txt file included
with the project.
Data about each slice of the pie can be stored in parallel arrays,
or as properties of a Slice object. The
example for this uses parallel arrays.
11.6 Programming Example – Trigonometric Functions
It is much easier to draw graphs of functions than it is to draw
histograms or pie charts. We simply need
to have a loop that goes through 360 degrees, calculates the
function for each degree, then draws the
function on the screen. However, some factors are necessary to
convert the value of the function for
each degree into coordinates on the screen.
For example, the sine of an angle varies from +1 to -1. If we
wish to plot the point (x,y) where x is the
28. angle and y is sine(x), we need to use a few factors to enlarge
the graph the image on the screen.
The following pseudocode shows a short algorithm for plotting
a sine curve. The value of the sine
function is multiplied by 100, giving us the range -100 to +100,
and it is added to 200 to position it on
the screen:
for(x =0.0; x <=360.0; x++)
{
y = 100.0 * Math.sin( Math.toRadians(x) );
plot (x,y)
}
The flowing image was drawn in a similar fashion, but instead
of plotting each point, a line was drawn
from each point on the curve to the next. The code for this is in
the NetBeans project SineCurve,
included with the files for this chapter. It uses several factors to
line things up on the screen, and adds a
few labels, as described in the comments in the source code.
CSCI 111 Chapter 11 Graphics pg. 16
29. We can also convert the drawing to polar coordinates using
parametric equations, and draw what is
known as a cosine rose. Basically, a cosine curve is wrapped
around a circle.
The image below shows this. The code for this is included in
the Netbeans project CosineRose. It starts
with a JOptionPane dialog box to ask the user for a factor that
will alter the image. The code uses a time
delay with try-catch blocks for exception handling, which is
described in the next chapter.
CSCI 111 Chapter 11 Graphics pg. 17
11.7 Programming Example – Abstract Computer Graphics
Using the graphics commands shown in this chapter and a little
creativity, it is fairly easy to create some
original computer artwork. Such as the example below:
Figurative art or abstract art can be drawn using various
graphics commands. Figurative art represents
30. things form the physical world. Abstract art represents more
abstract concepts. The Random Rectangles
image above is abstract; The Bedroom Window below is
figurative.
The art can also be dynamic, which means putting time delays
in the program to allow the user to see
the art being drawn or see the art changing while the program
runs.
Some of the examples shown here are abstract, dynamic art. To
see them in action run the program
included in the NetBeans projects RandomRectangles and
CirclePatterns included with this chapter.
CSCI 111 Chapter 11 Graphics pg. 18
Netbeans projects named RandomRoses and RandomCards are
also included with the files for this
chapter.
Warning: Some dynamic art programs flash on the screen and
could cause problems for people prone to
seizures, such as the CirclePatterns program.
31. CSCI 111 Chapter 11 Graphics pg. 19
Chapter Review
Section 1 of this chapter describes software and hardware used
for computer graphics including what a
graphics processing unit (GPU) is and why GPUs are used with
modern computers.
Section 2 describes the use of the java.awt.Canvas and
java.awt.Graphics classes
Section 3 is a long section describing how to work with of some
of the most commonly used drawing
methods in the Graphics class. It includes a discussion of
inverted Cartesian coordinates.
Section 4 shows an example of the Graphics class to create a
histogram. The process of laying out the
design for the histogram can be a tedious process. so students
are not expected to do this as part of this
class.
Section 5 shows an example using the Graphics class to create a
pie chart. The software included with
this chapter has a program to draw a pie chart from a data file.
Students can draw different pie charts
by changing the data file.
32. Section 6 demonstrates how to use the Graphics class to graph a
trigonometric function. It also has a
sample program that draws a cosine rose.
Section 7 discusses using the Graphics class to create abstract
and figurative computer artwork,
including still images and dynamic art.
Chapter Questions
1. What is a GPU? Why is it used for computer graphics?
2. What is the Canvas class in Java? Why is it used to in
conjunction with the Graphics class?
3. What is coordinate system is used for most computer
graphics? How does it compare to a Cartesian
coordinate system? Historically, how did this come to be used
for computer graphics?
4. What coordinates must be specified to draw a rectangle using
the drawrectangle() method?
5. How can we draw a filled rectangle using methods from the
Java Graphics class?
6. How can we draw a circle using methods from the Java
Graphics class? What about a triangle or
hexagon?
7. What is the system of measurement and direction for drawing
arcs of circle and ovals using the
33. drawArc() method?
8. How can we draw text on a Canvas using methods from the
Graphics class? How can we affect the
appearance of the text?
9. What is the difference between figurative and abstract
images?
10. What is the meaning of the term dynamic art with reference
to computer generated images?
CSCI 111 Chapter 11 Graphics pg. 20
Chapter Exercise
Your task for this chapter is to write a Java program using the
Java Graphics class to create an example
of a computer generated image. This is an opportunity for you
to explore computer graphics and
exercise some individual creativity.
You should submit well-documented code, along with a lab
report describing your work. What
happened in the process of exploration and design for your
project? How does your code work? How did
34. you use other features of Java, such as branching routines or
loops in your work? Tell us about the
thoughts behind your finished work. What influenced your
work?
Your work can be as simple or as complex as you would like,
but be careful about taking on something
that will be enormously time consuming. If you decide to work
on figurative art, It might help to start
with a single idea or concept, such as snowfall in the city, or
along the Schuylkill. Figurative art can also
be static or dynamic. Imagine how, for example, the Bedroom
Window example at the end of this
chapter could be subtly dynamic.
Your finished image for this project should be suitable for a
general audience.
This assignment will be the final project for our class, although
you will have a short assignment
regarding Exceptions.
CSCI 111 Chapter 11 Graphics pg. 21
Contents
Chapter 11 – Java Graphics
35. ...............................................................................................
............................ 2
Chapter Learning Outcomes
...............................................................................................
...................... 2
11.1 Overview of Graphics Programming in Java
................................................................................. 2
11.2 Using the java.awt.Canvas and java.awt.Graphics Classes
........................................................ 4
11.3 Using Methods from the Graphics Class
....................................................................................... 5
Onscreen
Coordinates.............................................................................
.............................................. 6
Drawing Lines
...............................................................................................
......................................... 7
Drawing Rectangles
...............................................................................................
................................ 7
Rectangles with Rounded Corners
...............................................................................................
......... 8
Ovals and Circles
...............................................................................................
.................................... 8
36. Drawing Arcs of Ovals and Circles
...............................................................................................
.......... 9
Drawing Polygons
...............................................................................................
................................. 10
Drawing Text
...............................................................................................
........................................ 10
Drawing Images from a Data File
...............................................................................................
......... 11
11.4 Programming Examples – a Histogram
....................................................................................... 11
11.5 Programming Example – a Pie Chart
...........................................................................................
13
11.6 Programming Example – Trigonometric Functions
..................................................................... 15
11.7 Programming Example – Abstract Computer Graphics
.............................................................. 17
Chapter Review
...............................................................................................
........................................ 19
Chapter Questions
...............................................................................................
................................... 19
37. Chapter Exercise
...............................................................................................
...................................... 20
An Introduction to
Computer Science with Java
Copyright 2013, 2019 by C. Herbert, all rights reserved.
Last edited November 22, 2019 by C. Herbert
This document is a draft of a chapter from Computer Science
with Java, written by Charles Herbert with the assistance of
Craig
Nelson. It is available free of charge for students in Computer
Science 111 at Community College of Philadelphia during the
Fall
2019 semester. It may not be reproduced or distributed for any
other purposes without proper prior permission.
Chapter 9 – Classes and Objects in Java
Contents
Chapter 9 – Classes and Objects in Java
...............................................................................................
........ 2
38. Chapter Learning Outcomes
...............................................................................................
...................... 2
9.1 Defining Classes of Objects in Java
...............................................................................................
2
9.2 Organizing Class Declarations in Java
........................................................................................... 6
Independent, De-Coupled Class Files
...............................................................................................
..... 6
Independent Classes in a Single Java
File.........................................................................................
..... 8
Nested Classes in a Single Java File
...............................................................................................
........ 8
Lab 9A – Creating multiple independent class files in IntelliJ
IDEA .......................................................... 9
9.3 Use of the Java Keyword this
...............................................................................................
....... 15
9.4 Example – Array of Objects: Monopoly Board Squares
.............................................................. 16
9.5 Abstract Methods, Abstract Classes, and Java Interfaces
........................................................... 23
39. Abstract Classes
...............................................................................................
................................... 23
Example of an Abstract Class – the Shape Class
................................................................................. 23
UML Diagrams for Inheritance and Abstract Classes
.......................................................................... 26
Java
Interfaces................................................................................
..................................................... 27
Interfaces in UML diagrams
...............................................................................................
................. 29
Java’s Comparable Interface
...............................................................................................
................ 29
Example – implementing Java’s Comparable Interface
.................................................................... 30
9.6 Copying Objects
...............................................................................................
........................... 32
A Copy Constructor in Java
...................................................................................... .........
.................. 33
Chapter Review
...............................................................................................
........................................ 34
40. Chapter Questions
...............................................................................................
................................... 34
Chapter Exercise
...............................................................................................
...................................... 35
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 2
Introduction to
Computer Science with Java
Chapter 9 – Classes and Objects in Java
This chapter describes how we can create our own classes in
Java. It includes creating classes of objects,
passing objects as parameters, use of the Java keyword this, and
implementing interfaces.
Chapter Learning Outcomes
Upon completion of this chapter students should be able to:
• Create a class of objects in Java as a collection of properties
and methods
that manipulate the properties.
• Create constructor, accessor, mutator, utility, and static
methods within Java
41. classes.
• Use objects of the students’ own creation in Java methods in
other classes.
• Describe the concept of an inner Class and create Java code
that uses inner
classes.
• Describe the use of the Java keyword this and properly use it
in Java
methods.
• Create and manipulate an array of objects in Java.
• Describe the concept of a Java interface and a Java abstract
class, the
purpose of the comparable interface and compareTo() method,
and
demonstrate their use in a Java class.
9.1 Defining Classes of Objects in Java
NOTE: Chapter 8 contains an introduction to the concepts of
object-oriented programming and should be
completed before working with this chapter.
The code that defines a class in Java is called a class
declaration, but it is also known as a class
42. definition. Class declarations in Java start with the keyword
class, then the name of the class, followed
by a set of braces enclosing the declarations for the properties
and methods in the class. Remember that
the Java naming convention is to start a class name with an
uppercase letter.
class ClassName {
// declare properties
// declare methods – with constructors first
) // end class ClassName
If a class is to be a public class, its name should preceded by
the visibility indicator public. Only one class
in each *.Java file may be public. If no visibility modifier is
used, then the class is package-private, and is
only accessible from within the package.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 3
Note about executable classes:
If a Java file has a main() method, it must be in a public class.
The public class then becomes an executable
class because of the presence of a main() method. The main()
method is a static method, and such a class is
43. an executable Java project class, in which all other methods in
the class are often static methods called from
the main() method. Such a class is not a class used to define
instances of objects, but an executable class
used to start software.
Usually the properties of an object are declared first in a class
declaration, followed by the methods.
Putting the set of property declarations together at the top of a
class declaration works like a data
dictionary, making it easier for someone reading a class
declaration to know what the properties of the
object are.
The constructors should be listed before other methods. As with
properties, this makes it easier for
someone reading the method to find them.
Example – Java Class Declaration
The following code shows a class declaration in Java for a Book
class of objects:
public class Book
{
// declare properties
44. private String isbn;
private String title;
private String subject;
private double price;
// constructor methods ******************************
public Book()
{
} // end Book()
public Book(String number, String name)
{
isbn = number;
title = name;
} // end Book(String number, String name)
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 4
// accessor methods *******************************
45. public String getTitle()
{
return title;
} // end getTitle()
public String getISBN()
{
return isbn;
} // end getISBN()
public String getSubject()
{
return subject;
} // end getSubject()
public double getPrice()
{
return price;
} // end getPrice()
46. // mutator methods ******************************
public void setTitle(String name)
{
title = name;
} // end setTitle()
public void setISBN(String number)
{
isbn = number;
} // end setISBN()
public void setSubject(String sub)
{
subject = sub;
} // end setSubject()
public void setPrice(double value)
{
price = value;
47. } // end setPrice()
// method to return information about the book as a String
public String toString()
{
return ("Title: " + title + "ISBN: " + isbn);
} // end to String()
} // end class Book
The Book class is properly encapsulated by making all of its
properties private. Only the public methods
may be used from outside of the class.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 5
The Book class has two constructors, a default constructor and a
constructor with two parameters,
number and name. A default constructor in Java is a
constructor with no parameters. Such a
constructor is often also a null constructor or a nullary
constructor. (Nullary is a term from mathematics
48. that indicates a function or operation with no operands.
Compare it to unary (with one operand) and
binary (with two operands). A null constructor sets up the
proper memory storage space for an instance
of an object, but the object's properties have null values – they
are empty.
A null constructor is simply a constructor with no code in the
method. Consider the following code,
which uses the default null constructor to create an instance of a
book:
Book myBook = new Book();
a new Book object with null values in its properties is created.
The variable myBook will contain a
reference to the new Book object.
A constructor whose declaration contains parameters is an
initializing constructor. It will create an
instance of an object with some or all the properties initialized,
depending on how the method is
defined.
Consider the following code which uses the initializing
constructor in the Book class to create an
instance of a book:
49. Book myBook = new Book("978-02-62031417", "Introduction to
Algorithms");
a new Book object with some initial values in its properties is
created. The variable myBook will contain
a reference to the new Book object. (This data is for a real
book, By Cormen, Leirson and Rivest, an is an
important work in Computer Science.)
These two methods with the same name but with different
parameters are an example of parametric
polymorphism, discussed in the previous chapter.
Each Java class that defines instance of an object must have a
constructor. If a class declaration in Java
does not contain any constructors, then the compiler will add a
default null constructor with an empty
method body.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 6
In the Book class example, the standard accessor methods
follow the constructor, and then the mutator
methods follow the accessors. There are no static methods or
properties. Static methods and properties
50. are normally listed first in the declarations of properties and
methods, but static methods are not often
used in classes that create instances of a class of objects.
The toString method could also be considered an accessor
method, since it returns information from the
properties of an object. It is a good programming practice to
include a toString() method for a class of
objects that returns identifying information about an object as a
String.
9.2 Organizing Class Declarations in Java
Java provides several different ways to organize and access
declarations for new classes of objects. In
this section we will examine three of those ways:
• independent, de-coupled class files with each class declaration
in its own file
• multiple classes in a single *.java file,
• inner classes, with one class declared inside another class.
Independent, De-Coupled Class Files
Unless there is a special reason to do otherwise, each class
should be
declared in its own file, creating independent de-coupled class
files. This is
51. the preferred approach to declaring objects in Java, as in many
object-
oriented programming languages.
Java source code should be contained in a text file ending with
the
extension “.java”. If the code contains a class with an
executable main()
method, it is an executable Java project file. However, most
classes in
object-oriented programming are not executable classes, they
are classes
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 7
that define objects to be used by other software. The Book
class in section 1 of this chapter is an
example – it is not executable and cannot be run by itself as a
program. It is used in conjunction with
other software to create instances of a book object.
Class files should have the same name as the class they are
defining -- the Book class is in the file
Book.java.
For true object-oriented programming –beyond trivial examples
52. like those found at the beginning of a
Java textbook or a Java language tutorial, we need both properly
defined classes of objects and a public
class with a main() method that allows us to execute our code.
Here is an example of an executable class that uses the book
class to create an instance of a book
object. It is the in the file BookProject.java from a project
named BookProject.
/* BookProject.java
* This file contains the excutable class for a project
* demonstrating the use of a Book object
* last edited November 20, 2019 by C. Herbert
* The file declaring the Book class must be visible to this Main
class.
*/
package BookProject;
public class Main {
public static void main(String[] args) {
53. // create an instance of the book class of objects
// note: this is a real book important in the history of
Computer Science
Book myBook = new Book("978-02-62031417","Introduction
To Algorithms");
// add a subject and a price
myBook.setSubject("Computer Science");
myBook.setPrice(64.95);
// print the information about the book
System.out.println(myBook.toString());
System.out.println("The price of the book is: " +
myBook.getPrice () );
System.out.println("The subject is: " + myBook.getSubject ()
);
} // end main()
} // end class BookProject
The two files – Book.java and BookProject.java are both part of
the same Java project, and are in the
54. same src folder within the project. The Book class in the
Book.java file is visible to main() method in the
Main class in BookProject.java. because the files are the same
folder (and in the same project).
This is the preferred way to organize object declarations in Java
– each class is in its own file. This
supports the notion of de-coupling objects so they more easily
can be used independently of one
another.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 8
Lab 9A starting on the next page shows you how to create this
example in IntelliJ IDEA. It demonstrates
creating a class in its own file in an IntelliJ project and then
accessing that class from the main() method
in the executable class.
Independent Classes in a Single Java File
Multiple classes can be defined in a single Java file, either one
after
another in sequence, or using nested classes. This works, but
remember, only one class in each file can be a public class. For
this
55. reason, placing each class in its own file is recommended
instead of
multiple classes in the same file, unless we wish to "hide" the
non-
public classes.
If we do want multiple independent class declarations in a
single file,
they should be placed in the file one after another as shown
below.
Typically, if one of the classes is an executable class with a
main()
method, that class is at the top of the file.
Only a public class can be accessed by other software. So, if we
have
multiple classes, then the private classes could be classes that
define
objects for use in the public class that we do not wish other
software to be able to see or use. In
essence, classes other thasn the one public class in the file are
encapsulated within the file.
However, the use of nested classes is preferred over having
multiple classes independently defined in
the same file.
56. Nested Classes in a Single Java File
One class can be defined within another class. The inside class
is known
as a nested class. If it is not a static class, it is called an inner
class. If it a
static class, it is known as a static nested class. The use of static
inner
classes is beyond what we wish to cover in this chapter, so we
will just
briefly look at inner classes.
An inner class in only visible to the class in which it is
contained. An
object defined by an inner class will only be useable within the
containing class. If we wish to have an encapsulated object that
is
"hidden" from other software, it can be declared in an inner
class. If we
want the object to be useable elsewhere, then it should be
defined in its
own class file.
No special notation is needed for an inner class – the class
declaration simple needs to be within
57. another class. The Java project InnerClassDemo, included with
this project, is an example of the use of
an inner class.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 9
Lab 9A – Creating Multiple Independent Class Files in IntelliJ
IDEA
This lab demonstrates how to create multiple, independent class
files in IntelliJ IDEA within the same
programming project. Our project will be named
"BookProject", the executable class will have intelliJ's
default name for the executable class "Main", and this will
contain the project's main() method. All of
this is similar to what you have done before. What's new is that
we will also create a second class file
within the project, Book.java, which will contain the class
declaration used to create instances of the
book class within the main() method in the Main.java file.
Objects must be defined in a class before they can be used. The
development of an IntelliJ IDEA project
with multiple classes occurs in three phases:
phase 1 – start the project
58. phase 2- create the classes that will define the objects to be
used in the project. Each class will be in its
ow file.
phase 3- create the code in the executable class that will use the
objects in the project.
The rest of this lab will walk you through this process, step by
step.
STEP 1.
Start IntelliJ IDEA, then from the opening menu, select
Create New Project.
A New Project window will open.
STEP 2.
On the new Project screen that appears,
make sure Java is selected to start a new
Java project, then click the [Next] button.
The New Project window will change to
show ask you about a project template.
59. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 10
STEP 3.
Click the checkbox to create project from
template, select the Command Line App template,
then click the [Next] button to continue.
The New Project window will change to ask you about
the name and location of your project files.
STEP 4.
The project name will be BookProject.
Fill in the Project name field with "BookProject", make
sure the Base package is also "BookProject", and
make sure the Project location is set to be what you
60. want it to be, as you would with any IntelliJ project.
It is usually best to make the package name and the
name of the project to be the same.
This example shows the desktop as the location.
Choosing a location fpr the project is up to you. You
may want to work on the desktop then copy the
project folder to a nother location for long term
storage.
When the data in the three fields is what you want it
to be, then click the [Finish] button to create your
project.
Now you should be able to see the main() method in the Main
class of your Java project.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 11
STEP 5.
Before going any further, add proper documentation to your
Main.java file, similar to the following:
61. /* Main.java
* This file contains the executable class for a project
* demonstrating the use of a Book object
* last edited November 20, 2019 by C. Herbert
* The file declaring the Book class must be visible to this Main
class.
*/
Also, label the closing braces for the main() method and for the
Main class:
} // end main()
} // end class Main
STEP 6.
Now that we have a project, we can create the Book class that
will be used to instantiate Book objects
within the project. We need the Book class to be defined before
we can create a Book object in the
main() method.
From the IntelliJ IDEA File menu, select New, then select Java
Class from the pop-up sub-menu that
62. appears.
A New Java Class file menu will appear, as shown below:
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 12
STEP 7.
Type "Book" in the space for the Name, and then double-click
Class in the menu to create a blank Java
class file named Book.java.
The Book.java file should appear in your IntelliJ editing
window as shown here:
Notice that a few things have happened. There are now two
tabs in the editing window –one for
Book.java, and one for Main.java. You can click on either tab
to see or to work with either file.
The BookProject folder within the src folder now has two
source code files in it – Book and Main.
The Book.java tab should be selected in the editing window, as
shown above, so that you can see the
Book.java class file. It contains the package declaration
63. indicating that this new file is part of the
BookProject package, and the Book class file, but the class has
no code in it yet.
STEP 8.
Before going any further, let's add proper documentation to this
class file, similar to the following:
/* Book.java
* This file contains the declaration for the Book class of
objects,
* as used in our textbook
* last edited November 20, 2019 by C. Herbert
* The file declaring the Book class must be visible to this Main
class.
*/
Also, label the closing brace for the class:
} // end class Book
When you are finished, you can save your work by Building the
project. It should build quickly, ssince
there is very little code in the project so far.
STEP 9.
64. Now we need to create the code to define the Book object. We
will need to add properties, constructor
methods, accessor methods, etc., to the Book class. The code
that we will use for this is shown starting
back on page 3 of this chapter. and in the file Book.java
included with the files for this chapter in Canvas.
You can cut and paste the code into your Book.Java class or
retype the code yourself. Copy and paste
the code defining the properties and methods between the
opening brace following the class header
and the and closing brace that we just labeled as the end of the
class.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 13
When you are finished, you code should match the code in the
file Book.java. Correct any errors that
may have occurred when you copied the code, then build the
project again to save your work.
STEP 10.
Now that we have a Book class, we can use it in the main()
method in the Main class to create a Book
object.
We will keep this simple. We wish to create a book with the
65. following information:
• ISBN: 978-02-62031417
• title: Introduction to Algorithms
• subject: Computer Science
• price: $64.95
We will instantiate a Book object with the initializing
constructor that uses ISBN and title as parameters.
We will use the variable myBook to refer to this book. Then, we
will use mutator methods to add values
for the subject and price properties of the object.
Let's turn the description from that last paragraph into
comments in Java.
// create an instance of the book class with an ISBN and title
// add a subject
// add a price
Click the tab to access the Main class in the IntelliJ Idea editor
and add these three comments to your
main() method. Your Main class should something look like
this:
66. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 14
STEP 11.
Now we can add the Java instructions to do what each comment
says to do, as follows:
// create an instance of the book class with an ISBN and title
Book myBook = new Book("978-02-62031417","Introduction To
Algorithms");
// add a subject
myBook.setSubject("Computer Science");
// add a price
myBook.setPrice(64.95);
STEP 12.
Our last step is to add code to print the information for
myBook. We will use the accessor methods
toString(), getSubject() and getPrice() to do this. Add the
following code to your main() method:
// print the information about the book
67. System.out.println(myBook.toString());
System.out.println("The price of the book is: " +
myBook.getPrice () );
System.out.println("The subject is: " + myBook.getSubject () );
The main() method in your Java project should now look like
this:
That's it, we are done! You now have a
Book class and software that
instantiates ad uses a Book object.
Build and run your software. Your
output should be similar to that shown.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 15
9.3 Use of the Java Keyword this
The Java keyword this may be used in a method to specify the
properties of the instance of the for
which the method has been invoked. It is most often used in a
method where a method variable or a
68. method parameter has the same name as a property of the
object.
Consider the following example from the Book class that
appeared near the beginning of this chapter.
The book class has a constructor with two parameters, number
and name as follows:
public Book(String number, String name)
{
isbn = number;
title = name;
} // end Book(String number, String name)
However, what happens if the two parameters have the same
name as the object's properties, like this:
public Book(String isbn, String title)
{
isbn = isbn; // note that these two lines are incorrect
title = title; // no errors, but they don’t work as expected
} // end Book(String isbn, String title)
How does the computer know whether isbn refers to parameter
69. or to the objects isbn property? The
statement isbn = isbn; can cause confusion for a compiler and
for a person reading the method. The
compiler will assume that isbn is the name of the variable or
parameter, and not the name of an object’s
property. It makes sense to the compiler and no error is
generated, but it just doesn’t work as we
wanted it to work. It sets the variable isbn equal to itself and
does not change the object's isbn property.
The keyword this is designed to solve the problem. this.isbn
will refer to the property isbn for the
instance of the object that was used to invoke the method.
Here is the method with the keyword this:
public Book(String isbn, String title)
{
this.isbn = isbn; // note: this works as expected
this.title = title;
} // end Book(String isbn, String title)
The keyword this can always be used to indicate an object's
property, even if it doesn't have the same
name as a method parameter or method variable. Even though it
70. always appropriate when referring to
properties of an object, we only need to use it if a property and
a variable or Parmenter have the same
name. Some programs always use this, while others only use
this when necessary.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 16
9.4 Example – Array of Objects: Monopoly Board Squares
As we saw in Chapter 8, each element in an array of objects is a
reference variable holding the address
of an object. The example below demonstrates the creation of
an array of objects.
In this example we will create an array of
squares for a Monopoly board, then place the
squares in an array of objects. First, we must
define a class for the squares, and then we can
place them in an array.
We will start with a description of the squares
and a UML diagram of the class.
There are 40 squares on a Monopoly board, as
71. shown here.
There are different types of squares:
• Property. These squares can be bought
and sold. A player who lands on a
property must pay rent. Each property
belongs to a color group. A Monopoly
property has the attributes name, price,
rent, color and owner.
• Railroad. Railroads can also be bought and sold, but the rent
for a player who lands on a
railroad square depends on the number of railroads in
possession of the owner. These squares
only have a name and an owner.
• Utility. Utilities can be bought and sold. The rent depends on
the roll of the dice when a player
lands on the square. Utilities, like railroads, only have the
properties name and owner.
• Community squares. There are several other squares that can
be grouped together as
community squares that do not have an individual owner and
cannot be bought or sold. The
72. action to be performed when a player lands on a community
square depends in the specific
square. They each only have a name, but no owner, price, or
fixed rent. The community squares
include:
o two card squares (Chance and Community Chest) with cards
to determine what happens
when a player lands on one of these squares.
o two tax squares (Income Tax and Luxury Tax) that each have
a formula for determining the
tax a player pays to the bank when landing on one of these
squares.
o two free squares – Just Visiting and Free Parking on which
nothing happens. The game's
jail is on the Just Visiting square.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 17
o The Go square, on which the game starts. Players are paid
$200 each time they go around
the board and pass the Go square.
o a Go to Jail square, which sends a player to jail.
73. We are going to create a simplified version of the game with an
array of board square objects with
simplified properties. This is typical in software development.
A complex piece of software might be
developed in stages, with a simplified design used for early
stages and complexity added during later
stages of development.
For our simplified version of the game, the rent for railroads
will be fixed at $25, the rent for utilities will be
fixed at $15, and the community squares will be inactive, in
effect being all free parking. Each square will
have five properties: name, type, rent, price and color.
Our simplified game will have four types of squares: property,
railroad, utility, and community. We will not
keep track of who owns which square in this version of the
game.
Information about each square for our simplified game is
summarized in the following table.
Name type Rent price color
Go community 0 0 null
Mediterranean Ave. property 2 60 Dark Purple
Community Chest community 0 0 null
74. Baltic Ave. property 4 60 Dark Purple
Income Tax community 200 0 null
Reading Railroad railroad 25 200 null
Oriental Ave property 6 100 Light Blue
Chance community 0 0 null
Vermont Ave. property 6 100 Light Blue
Connecticut Ave. property 8 120 Light Blue
Jail/Just Visiting community 0 0 null
St. Charles Place property 10 140 Light Purple
Electric Company utility 10 150 null
States Ave. property 10 140 Light Purple
Virginia Ave. property 12 160 Light Purple
Pennsylvania Railroad railroad 25 200 null
St. James Place property 14 180 Orange
Community Chest community 0 0 null
Tennessee Ave. property 14 180 Orange
New York Ave. property 16 200 Orange
Free Parking community 0 0 null
75. Kentucky Ave. property 18 220 Red
Chance community 0 0 null
Indiana Ave. property 18 220 Red
Illinois Ave. property 20 240 Red
B & O Railroad railroad 25 200 null
Atlantic Ave. property 22 260 Yellow
Ventnor Ave. property 22 260 Yellow
Water Works community 10 150 null
Marvin Gardens property 24 280 Yellow
Go To Jail community 0 0 null
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 18
Pacific Ave. property 26 300 Green
No. Carolina Ave. property 26 300 Green
Community Chest community 0 0 null
Pennsylvania Ave. property 28 320 Green
Short Line Railroad railroad 25 200 null
Chance community 0 0 null
76. Park Place property 25 350 Dark Blue
Luxury Tax community 100 0 null
Boardwalk property 50 400 Dark Blue
We wish to create a BoardSquare class of objects, based on the
information in the table above. We can
see that there we need are five data properties for each square:
• name – the name of the square
• type – the type of the square. There are six types: property,
railroad, utility, plain, tax, and toJail
• price – the cost to buy the square. A price of zero means the
square is not for sale.
• rent – the rent that a player who lands on the square must pay.
• color – the color of the square. only property squares have
color, the rest are null.
We need public methods to get each property, but not to set
each property, since users will not be able
to change the properties of each BoardSquare. The
BoardSquare's values will be set by a constructor. In
this case, the set of methods will be simple – two constructors
(one null constructor and one initializing
constructor) and the accessor method for each BoardSquare’s
77. property, plus a toString() method.
We will use Strings for most properties. The price and the rent
will be integers. Here is an annotated
UML diagram for the BoardSquare class:
BoardSquare (board squares for a Monopoly game)
- name: String
- type: String
- price: int
- rent: int
- color: String
name of the square
property, railroad, utility, or community
color group; many are null
+ BoardSquare(): void
+ BoardSquare(String, String, int, int, String): void
+ getName(): String
+ getType(): String
+ getPrice() int
+ getRent() int
+ getColor:(() String
+ toString:() String
(name, type, price, rent and color)
78. returns data about the square as a String
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 19
Here is the code for the corresponding class of BoardSquare
objects:
/* BoardSquare.java
* CSCI 111 Fall 2019
* last edited November 22, 2019 by C. Herbert
*
* This file defines the BoardSquare class
* for BoardSquare objects in a simplified version of a
Monopoly game.
* The BoardSquare class is required for the project to work
properly.
*
* This is for teaching purposes only.
* Monopoly and the names and images used in Monopoly are
* registered trademarks of Parker Brothers, Hasbro, and others.
79. */
package monopoly;
public class BoardSquare {
private String name; // the name of the square
private String type; // property, railroad, utility, or
community
private int price; // cost to buy the square; zero means not
for sale
private int rent; // rent paid by a player who lands on the
square
private String color; // many are null; this is not the Java
Color class
// constructors
public BoardSquare() {
name = "";
type = "";
price = 0;
rent = 0;
color = "";
80. } // end Square()
public BoardSquare(String name, String type, int price, int
rent, String color) {
this.name = name;
this.type = type;
this.price = price;
this.rent = rent;
this.color = color;
} // end BoardSquare()
// accessors for each property
public String getName() {
return name;
} //end getName()
public String getType() {
return type;
} //end getType()
81. public int getPrice() {
return price;
} //end getPrice()
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 20
public int getRent() {
return rent;
} //end getRent()
public String getColor() {
return color;
} //end getColor()
// a method to return the BoardSquare's data as a String
public String toString() {
82. String info;
info = (name + ", " + type + ", " + price + ", " + rent + ", "
+ color);
return info;
} //end toString()
} // end class BoardSquare
//***************************************************
************************
The executable class in the Monopoly project is named
Monopoly and is in the file Monopoly.java. It
uses the BoardSquare class to create an array of BoardSquares.
The main() method:
• creates an array of 40 BoardSquares and assigns the variable
square to refer to the array. The
properties of the BoardSquares are null at the time it is created.
• calls the method loadArray(), which initializes the properties
of the 40 BoardSquares from data
in a file named "squares.txt"
• calls the method printArray(), to test the software by printing
the properties of each element in
83. the square[] array.
/* Monopoly.java
* CSCI 111 Fall 2019
* last edited November 22, 2019 by C. Herbert
*
* This file contains the executable class Monopoly
* for a simplified version of a Monopoly game.
* It requires access to the BoardSquare class to work properly.
*
* The software creates an array for 40 BoardSquares and loads
data
* into the array from a simple text data file
*
*It also has code to test the program by printing the data from
the array
*
* This is for teaching purposes only.
* Monopoly and the names and images used in Monopoly are
* registered trademarks of Parker Brothers, Hasbro, and others.
84. */
package monopoly;
import java.util.*;
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 21
public class Monopoly {
public static void main(String[] args) throws Exception {
// create an array for the 40 squares on a Monopoly board
BoardSquare[] square = new BoardSquare[40]; // array of
40 monopoly squares
// call the method to load the array
loadArray(square);
// test the code by printing the data for each square
printArray(square);
85. } // end main()
//***************************************************
********************
// method to load the BoardSquare array from a data file
public static void loadArray(BoardSquare[] sq) throws
Exception {
// declare temporary variables to hold BoardSquare
properties read from a file
// each variable corresponds by name to a property of a
BoardSquare object
String inName;
String inType;
int inPrice;
int inRent;
String inColor;
// Create a File class object linked to the name of the file
to be read
java.io.File squareFile = new java.io.File("squares.txt");
86. // Create a Scanner named infile to read the input stream
from the file
Scanner infile = new Scanner(squareFile);
/* This loop reads data into the array of BoardSquares.
* Each item of data is a separate line in the file.
* There are 40 sets of data for the 40 squares.
*/
for (int i = 0; i < 40; i++) {
// read data from the file into temporary variables
// read Strings directly; parse integers
inName = infile.nextLine();
inType = infile.nextLine();
inPrice = Integer.parseInt(infile.nextLine());
inRent = Integer.parseInt(infile.nextLine());
inColor = infile.nextLine();
// initialze each array element with the BoardSquare
initializing constructor
sq[i] = new BoardSquare(inName, inType, inPrice,
inRent, inColor);
87. } // end for
infile.close();
} // endLoadArray
//***************************************************
********************
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 22
// test method to print data from the array of BoarsSquares
public static void printArray(BoardSquare[] sq) throws
Exception {
// print header above each row
System.out.println("Data from the array of Monopoly
board squares.n");
System.out.printf("%-22s%-12s%6s%6s%14s%n", "name",
"type", "price", "rent", "color");
88. System.out.println("************************************
****************************");
// print data in formatted columns, one square per row
for (int i = 0; i < 40; i++) {
System.out.printf("%-22s", sq[i].getName());
System.out.printf("%-12s", sq[i].getType());
System.out.printf("%6d", sq[i].getPrice());
System.out.printf("%6d", sq[i].getRent());
System.out.printf("%14s%n", sq[i].getColor());
} // end for
} // end printArray
//***************************************************
********************
} // end class BoardSquare
//***************************************************
************************
Each element in the array square will now be a reference
89. variable, holding the memory address where
the corresponding BoardSquare object is actually stored in
memory.
square[0] square [1] square [2] square [3] . . .
4000H 4128H 4224H 4380H . . .
square[0]
name: Go
type: community
rent: 0
price: 0
color: null
square[1]
90. name: Mediterranean Ave.
type: property
rent: 2
price: 60
color: Dark Purple
square[2]
name: Community Chest
type: community
rent: 0
price: 0
color: null
square[3]
name: Baltic Ave.
type: property
rent: 4
price: 60
color: Dark Purple
91. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 23
9.5 Abstract Methods, Abstract Classes, and Java Interfaces
An abstract method in Java is a method that only has a method
header – including its return type,
name, and parameter list – but no method body. It’s really not
a method, just information about the
method. Abstract methods are used to create Java interfaces
and Abstract classes, which we learn more
about in just a moment.
The header for an abstract method starts with the keyword
abstract and ends with a semicolon, such as
in the following examples:
abstract double getArea();
abstract void draw();
abstract void resize();
Each of these three might be used in a program that draws
shapes on the screen.
A concrete method is a method that is not abstract – in other
words, the normal methods that we have
been using so far.
Obviously, abstract methods can’t do anything, but can they
form the basis for extensions of Java
92. Abstract classes and implementations of Java interfaces that can
do things.
Abstract Classes
An abstract class is a class that cannot be instantiated – in other
words, no objects of the class can be
created. An abstract class serves as the basis for subclasses that
can be instantiated.
An abstract class may contain one or more abstract methods.
Any class that contains at least one
abstract method must be declared as an abstract class. The
following example shows how and why
abstract classes are used.
Example of an Abstract Class – the Shape Class
Imagine that we wish to have a graphics program that can draw
a variety of shapes on the screen, and
can give us information about the shapes it draws – color,
perimeter, area, location, and so on. The
shapes will be in different classes that have different properties.
For example, a circle will have a radius, whereas a square will
have a side, and a rectangle will have a
long side and a short side. All of the shapes will have an area, a
perimeter, a color, and a location.
93. The methods to draw the shapes on the screen will work
differently for different shapes. The software
will use the location of the center of a circle and its radius to
draw a circle, while it will use the location
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 24
of the top left corner of a square and the length of its side to
draw a square. The classes for rectangles,
ellipses, regular hexagons, triangles, parallelograms, and so on,
will all use different information to draw
the shapes, but they will all have draw methods; The same is
true for area methods and perimeter
methods; each class will have them , but they will not all work
the same way.
This is an obvious case where inheritance can be used. We can
set up a parent class, named Shape, with
subclasses Circle, Square, Rectangle, and so on. All of the
objects in the graphics system will be objects
of one of the subclasses of Shape – they will all be circles,
squares, rectangles, and so on. No objects of
the parent class Shape will be created. A few properties – such
as location, color, area and perimeter –
will be common to all shapes but other properties and most
94. methods will be different for each subclass.
This is the perfect case for an abstract class. We will declare
Shape to be an abstract class, which means
there will be no Shape objects. The objects will be in
subclasses of Shape . We will put the common
properties in the Shape class to be inherited by the subclasses.
We will also give the shape class abstract methods for draw,
area, and perimeter, which will tell
programmers that the subclasses must implement these methods.
Concrete classes that are subclasses
of abstract classes must implement the abstract classes inherited
from the abstract parent class.
Here is what the abstract parent class Shape will look like:
abstract class Shape {
// declare properties
Point location; // an object of type Point has an x and y
coordinate
Color color; // using Java’s built in Color class
double area;
double perimeter;
95. // declare concrete methods -– accessors for location and color
Point getLocation() {
return location;
}
Color getColor() {
return color;
}
// declare concrete methods – mutators for location and color
void setLocation(Point location) {
this.location = location;
}
void setColor(Color color) {
this.color = color;
}
// declare abstract methods
abstract void draw();
96. abstract double calculateArea();
abstract double calculatePerimeter();
}// end abstract class Shape
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 25
The abstract class Shape can now be used as the basis for
subclasses. The subclasses will inherit the four
properties – location, color, area, and perimeter – and the
concrete methods, and they must implement
the abstract methods draw(), calculateArea(), and
calculatePerimeter(). The code for the Circle class,
minus some of the details, is shown below.
class Circle extends Shape {
// declare Circle specific properties
private double radius;
private Point center; // center and location will be the same
point.
// constructors
public Circle() {
97. radius = 0;
area = 0;
perimeter = 0;
} // end Cirlce()
public Circle(Point location, double radius, Color color) {
this.location =location;
this.radius = radius;
this.color = color;
// re-calculate area and perimeter whenever radius changes
area = calculateArea();
perimeter = calculatePerimeter();
} // end Circle( --- )
// add additional accessors
public double getRadius() {
return radius;
} // end getRadius()
98. public double getCenter() {
return center;
} // end getCenter()
public void setRadius(double radius) {
this.radius = radius;
// re-calculate area and perimeter whenever radius changes
area = calculateArea();
perimeter = calculatePerimeter();
} // end setRadius
// add additional mutators
// implement classes that were abstract in the super class
(parent class)
public void draw(){
// put the code here to draw a circle
} // end draw()
99. CSCI 111 Chapter 9 – Classes and Objects in Java pg. 26
private double calculateArea() {
// area = π * r^2
return Math.PI * radius * radius;
} // end calculateArea()
private double calculatePerimeter() {
// area = 2 * π * r
return Math.PI * 2.0 * radius;
} // calculatePerimeter()
// add additional methods for the Circle class here
} // end class circle
To summarize the use of Abstract classes:
• Abstract methods are methods that have no body, just the
method header.
• An abstract class is a class that has at least one abstract
method.
• An Abstract class cannot be instantiated – no objects of that
100. class can be created.
• Abstract classes are the basis for concrete classes that can be
instantiated.
• An Abstract class may contain properties and concrete
methods that subclasses have in
common, and abstract methods for other methods that the
subclasses must have, but which will
work differently in different subclasses.
UML Diagrams for Inheritance and Abstract Classes
We use arrows to denote subclass relationships (inheritance) In
UML diagrams, pointing from the
subclasses to the superclass. The arrowheads are supposed to
be open arrowheads , but often
solid arrowheads are used because they are much easier to draw.
The simplified UML diagram
below shows this. Book and and EMail both are subclasses of
Document.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 27
Technically, the UML standard only calls for abstract class
names and abstract method names to be
italicized, but often people put the word “abstract” with the
101. names to make it more obvious that they
are abstract.
Java Interfaces
Abstract methods can also be used in Java Interfaces. Java
Interfaces are very similar to abstract classes,
but they have two differences:
1. Interfaces can only have abstract methods, not concrete
methods. Interfaces can have
constants, but not properties or concrete methods. (An abstract
class can have concrete
methods as well as abstract methods.)
2. Interfaces are implemented not inherited; they are not used as
super classes. A concrete class
can implement more than one interface.
Interfaces have no constructors, and are not classes that can be
instantiated. They provide a standard
set of method calls for other classes.
A class implements an Interface by using the phrase
”implements [interface name]” immediately after
the name of the class in the class declaration.
Java interfaces are used to provide a common set of method
calls for use within many classes. In
102. essence, they form a contract that says “This class will include
the methods listed in the interface, with
the same method names, parameters and return types.”
Effectively, an interface in Java is a list of
abstract methods that will be implemented in any class that
implements the interface.
Imagine that we have several major electronic companies
making burglar alarms, cable television boxes,
microwave ovens, and so on, all of which use an electronic
clock with a display and a programmable
clock chip made by one manufacturer. The manufacturer could
publish a Java interface showing how to
invoke the methods to program the chip. The various other
manufacturers could include the interface
in the Java code for their devices, so that programmers creating
software for the various systems could
all use the same method names, parameters, etc, for any clock
software, making all of the system more
compatible with one another.
The code below shows a clock interface.
interface Clock {
void setTime(int hours, int minutes, int second);
103. void setHours(int hours);
void setTimeZone(int zone);
void setMinutes(int minutes);
void setSeconds(int seconds);
int getHours();
int getMinutes();
int getSeconds();
int getTimeZone();
} // end interface Clock
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 28
By publishing the interface, the clock chip manufacturer is
telling others : “these methods are
guaranteed to work in our system.” The Java software in the
clock would implement this interface, as
would any software in any compatible system that also declares
that it implements the interface.
To implement an interface, the class header should include the
declaration “implements [name of
104. interface]” immediately after the class name. For example a
class named Timer that implements the
Clock interface might have a class declaration that starts like
this:
Public class Timer implements Clock
{
// body of the Timer class goes here – properties and methods
as usual
}
This tells the world that the Timer class has code implementing
all of the abstract methods in the Clock
interface. Someone who knows the Clock interface would then
know how to invoke and use the similar
methods in Timer. In a similar manner, someone who knows
the Clock interface would also know how
to use the related methods in any system that implements Clock
– household appliances, entertainment
systems, communications equipment, and so on.
In some systems, the interface that specifies the behavior is
called the supplier, and the class that
implements the behavior is called the client.
In the modern world, with so many systems interacting with one
105. another all around the Earth via the
Web, through mobile devices, via telephone and radio systems,
and so on, Java interfaces go a long way
toward ensuring some compatibility among software systems.
Interfaces are one of the reasons the
Java language is used so widely in so many large complex
computer systems.
To summarize the use of Java interfaces:
• An interface is a collection of methods, similar to those found
in a class, but all of the interface’s
methods are abstract methods.
• An interface could also include properties and constants, but
often only has abstract methods.
• A class that implements an interface will have methods that
match the abstract methods in the
interface, with the same method names and matching
parameters.
• An interface is like a contract, with any class that implements
the interface guaranteeing that
the methods listed in the interface will work in the class.
• classes can implement more than one interface.
• interface implementation is independent of inheritance.
Interfaces cannot be inherited; a class
106. cannot extend an interface.
• a programmer declares a class will implement an interface by
including “implements [interface
name]” immediately after the class name, such as in “public
class Timer implements Clock { … ”.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 29
Interfaces in UML diagrams
The implementation of interfaces in UML diagrams is shown by
using an arrow with a dotted line
pointing from a class to any Interfaces it implements. In the
following simplified example, both the
Professor class and the Student class implement the Person
interface:
Java’s Comparable Interface
One commonly used Java interface is the Comparable interface,
whose only method is the CompareTo()
method. The CompareTo() method compares two objects in a
class and returns an integer.
The integer returned by a.compareTo(b) will be:
107. • a negative number if a comes before b;
• a zero if a equals b;
• a positive number if a comes after b.
An example of how this is used is the The String class
CompareTo() method, which uses the lexicographic
order (alphabetic order) of the Unicode characters in the String
to compare them. It is most often used
in an If statement, such as in this code from the BubbleSort
demo example in Chapter 6:
if ( a[i+1].compareTo(a[i]) < 0 ) // if the two items are out
of order
{
// swap the two items and set swapped to true
c = a[i];
a[i] = a[i+1];
a[i+1] = c;
swapped = true;
} // end if
The pattern of use for the compareTo() methods in if statement
108. basically is:
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 30
• if (a.compareTo(b) < 0) // then a comes before b.
• if (a.compareTo(b) == 0) // then a equals b.
• if (a.compareTo(b) > 0) // then b comes before a.
But this only works if we implement the compareTo() method in
a way that tells the computer how to
compare two items in a newly defined class, as the String class
does. How will objects in a new class be
compared?
To implement the comparable interface in a new class, we need
to include code for the compareTo()
method in a class declaration telling the computer how to
compare two items in the new class. The
following example shows how to do this with the Book class
from the beginning of the chapter.
Example – implementing Java’s Comparable Interface
Here is part of the class declaration for the Book class:
public class Book
{
109. // declare properties
private String isbn;
private String title;
private String subject;
private double price;
// constructor methods ******************************
public Book()
{
} // end Book()
the rest of the class declaration follows this . . .
For the compareTo() method to work, we need to decide what
to use as the basis for the order of our
books. We can use any property that already has a predefined
order, such as the ISBN or the title, which
are Strings. If the new class has a property that is a key field,
then that should be used as the basis for
the compareTo() method. A key field is a field that has a
unique value for each instance of an object.
110. Your Jnumber at CCP is an example of a key field – no two
students can have the same Jnumber. Social
security numbers, bank account numbers, and Vehicle
Identification Numbers (VIN) are all examples of
key fields.
isbn is a key field. It can be used to compare two objects. The
following code shows how to implement
the compareTo() method in the book class using the String
property isbn:
/* compareTo() method using ISBN as the basis for ordering
Book objects
* a.compareTo(b) compares Book a to Book b
public int compareTo(Book b)
{
int x;
x = this.isbn.compareTo(b.isbn);
return x;
} // end Book()
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 31
111. In the code shown here, this.isbn is the isbn property for the
Book object invoking the method. In code
outside of the class, Book object a can be compared to Book
object b this way - a.compareTo(b);
The isbn property is a String, so one isbn is compared to
another in the method by using the String class
compareTo() method. this.isbn.compareTo(b) invokes the
String compareTo() method for this.isbn. The
Book compareTo() method then returns the result of that String
comparison. The result is that Book
class objects will now be compared by their isbn properties
whenever a program uses compareTo() with
Book class objects.
The Book class header can now include the “implements
comparable” phrase:
public class Book implements Comparable
{
// declare properties
private String isbn;
private String title;
private String subject;
private double price;
112. // constructor methods ******************************
public Book()
{
} // end Book()
. . . other methods would follow here, including
public int compareTo(Book b)
{
int x;
x = this.isbn.compareTo(b.isbn);
return x;
} // end Book()
the rest of the class declaration follows this . . .
We can include the Book compareTo() method in the Book class
declaration without implementing
Java’s comparable interface, so why should we bother to do so?
The answer is to let programmers know
113. that our class of objects can be compared and ordered using this
standard method. By putting a
compareTo() method in the Book class declaration and
including the “implements comparable” phrase
with the Book class header, we are telling other programmers
that Book objects can be compared to
one another, so they can be sorted, etc.
Think of it like a badge worn by a soldier. A soldier who is a
properly trained combat parachutist wears a
badge with combat jump wings on his uniform, indicating he is
a trained parachute jumper. In a similar
manner, the “implements comparable” phrase indicates that a
class includes a proper compareTo()
method.
Please note that the comparable interface is included in the
standard Java.lang package, so it can be
used without any import statement. Other Java interfaces, such
as some of those used in GUI
programming, may need import statements to work in you code.
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 32
9.6 Copying Objects
114. We have seen that a reference variable is used to refer to the
location where the details of an object are
actually stored. For example, imagine that we have two objects
from the Book class, bookA and bookB.
Each variable will point to the memory location where the data
for its object is stored.
In chapter 8 we saw that setting BookB equal to BookA with
the statement BookB = BookA; changes
the value of the reference variable so that they both point to
BookA. The old data from BookB is lost.
bookA
bookB
115. But what if we want BookB to be a copy of BookA? The copy
shown above, where the reference is
copied so that two variables refer to the same object in memory
is known as a shallow copy. Copying all
of the properties of one object to another object of the same
type is known as a deep copy. A deep copy
bookA
bookB
bookA
isbn: 978-1400033416
title: Beloved
subject: fiction
price: 23
bookB
isbn: 978-0316769174
title: The Catcher in the Rye
subject: fiction
116. price: 14
bookB
isbn: 978-0316769174
title: The Catcher in the Rye
subject: fiction
price: 14
bookA
isbn: 978-1400033416
title: Beloved
subject: fiction
price: 23
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 33
copies the state of one object to another. The diagram below
shows what a deep copy would look like.
We need to write a method to perform a deep copy.
117. Here is a method to perform a deep copy for the Book class:
public void copy(Book source)
{
this.isbn = source.isbn;
this,title = source.title;
this.subject = source.subject;
this.price = source.price;
)
The code to copy BookA to BookB would then look like this:
BookB.copy(BookA);
All of the properties of BookA are copied to BookB.
A Copy Constructor in Java
Once we have a copy() method in our class, we can easily set up
a copy constructor. A copy constructor
is a constructor that creates a new instance of an object and
copies the state of an existing object into
the new object. It creates a new copy of an object initialized
118. with all of the properties of the object it is
copying. The code for a copy constructor in the Book class
would like this:
Book( Book source)
{
this.copy(BookA);
)
Of course, this only works when we have already have a copy()
method. A copy constructor is used like
this:
Book bookD = new Book(bookA);
It is very useful to include a copy method and a copy
constructor in declarations for new classes.
bookA
bookB
bookB
isbn: 978-1400033416
title: Beloved
subject: fiction
119. price: 23
bookA
isbn: 978-1400033416
title: Beloved
subject: fiction
price: 23
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 34
Chapter Review
Section 1 of this chapter described class declarations for a new
class of objects in Java. Key terms
included: class declaration and default constructor. (Note: Most
of the new key terms for this topic
were introduced in the previous chapter.)
Section 2 discussed two ways to organize class declarations in
Java code: multiple classes in a single
*.java file, and inner classes. Key terms included inner class
and nested classes.
Section 3 described appropriate use of the Java Keyword this.
Section 4 described how arrays of objects work in Java, using
120. reference variables.
Section 5 discussed the Java abstract methods and their use in
Abstract Classes and Java interfaces,
including the use of Java’s Comparable interface. Key terms
included: abstract method, concrete
method, abstract class, interface, and key field.
Chapter Questions
1. By what other name is a Java class declaration also known?
What is a default constructor? What
happens if a Java Class declaration does not have a constructor?
2. In a .java file, when should a class be public? What class is
always public in a .java file? How many
classes in a .java file can be public?
3. How are inner classes declared in Java? When is an inner
class a good idea, and when is it a bad idea?
4. What does the keyword this refer to in a Java method?
When should it be used?
5. What is a static property? How are static properties invoked?
6. What is actually stored in an array of objects in Java?
7. How is an abstract method declared in Java? How is it
different from a concrete method?
8. How is an object of an abstract class instantiated in Java?
121. What are abstract classes used for? What
classes must be declared as an abstract class?
9. What do we know about all of the methods in a Java
interface? What does implementation of an
interface by a class guarantee for a programmer using the class?
How many interfaces can a class
implement?
10. How is inheritance indicated on a UML diagram? How is
implementation of an interface indicated?
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 35
Chapter Exercise
Creating A Player Class for a Monopoly Game
The Java project Monopoly in the files for this chapter, has two
classes described earlier in the chapter –
the executable class Monopoly.java and BoardSquare.java
which defines a BoardSquare object.
Your task is to create a new class for a Player object in a
monopoly game, and to revise the existing
Monopoly project to test the player class by moving the player.
We are not implementing a complete
122. Monopoly game, but just creating a Player class and testing how
it works within the project.
You should:
1. Design and create the class declaration for the Player class
according to the annotated UML
diagram below, and add it to the IntelliJ Monopoly project in a
new Java class file.
2. Modify the executable Monopoly class to test the player, as
follows:
a. you should instantiate a player object. ( … such as, Player p1
= new Player();
p1 is just an example. You can decide what to name the
variable.)
b. initialize the player’s location to be square 0, the Go square.
the player’s location will be
the square that the player’s token is currently on.
c. initialize the players name and token with values you choose,
such as "Joe" and "the
race car". Initialize the players balance to be 1500.
d. print the initial data for the Player, such as
the race car is on GO. Joe's Balance is $1,500.
e. create a loop to move the player 10 times. The loop should:
123. i. pick two random numbers between 1 and 6 and add them
together to simulate
the rolling of a real pair of dice.
ii. move the player (change location) to the new square by
adding the player's
location to the value rolled by the dice. (If the value is greater
than 39, then
subtract 40. This accounts for starting again at the start of the
board.)
The code could look like this:
newLocation = p1.getLocation() + roll;
if (newLocation > 39)
newLocation = newLocation - 40;
p1.setLocation(newLocation);
iii. subtract the square's rent from the player's balance,
something like this:
newBalance = p1.getBalance() -
square[newLlocation].getRent();
p1.setBalance(newBalance);
CSCI 111 Chapter 9 – Classes and Objects in Java pg. 36
124. We are subtracting rents but not adding anything to the player's
balance.
Remember, our purpose is just to test the player object.
iv. print a message telling us the roll of the dice, the new
location, it's rent, and
new balance, such as:
Joe rolled 8. The Race Car is on Vermont Ave. The rent is $6.
Joe's now has $1,494.
Remember, this is the first part in building a Monopoly game in
Java so we are only testing the player
class object by moving the player on the board. Things like
picking a card if the player lands on Chance,
buying and selling properties, collecting $200 for passing Go,
and so on, are not part of this project. In a
real development situation, those things would be added in
another phase of the project once the
BoardSquare and Player objects work properly. Graphics (and
sound) would also be added later. Don’t
get carried away with fancy features at this point and make the
assignment harder than it needs to be.
Player (player for a Monopoly game)
- name: String
- token: String
125. - location: int
- balance: int
name of the player
racecar, wheelbarrow, battleship, top hat, etc.
the number of the square the player is on
initialized to zero
the player’s current bank balance
initialized to 1500
+ Player(): void
+ Player(String, String, int, int): void
+ getName(): String
+ getToken(): String
+ getLocation() int
+ getBalance() int
+ setName(String): void
+ setToken(String): void
+ setLocation(int): void
+ setBalance(int): void
+ toString:() String
(name, token, location, bank balance)
returns data about the player as a String