java fundamentals for non-c programmers - … · java fundamentals for non-c programmers core java...

69
Java Fundamentals for Non-C Programmers Student Workbook

Upload: lyliem

Post on 12-May-2018

280 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentalsfor

Non-C ProgrammersStudent Workbook

Page 2: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page ii Rev 5.2.1 © 2013 ITCourseware, LLC

Java Fundamentals for Non-C Programmers

Published by ITCourseware LLC, 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112

Contributing Authors: Keith Blackwell, Danielle Hopkins, Channing Lovely, Jamie Romero, RobRoselius, Robert Seitz, and Rick Sussenbach.

Editors: Danielle Hopkins and Jan Waleri

Editorial Assistant: Ginny Jaranowski

Special thanks to: Many Java instructors whose ideas and careful review have contributed to the quality ofthis workbook, including Jimmy Ball, Larry Burley, Roger Jones, Joe McGlynn, Jim McNally, MikeNaseef, Richard Raab, and Todd Wright, and the many students who have offered comments, suggestions,criticisms, and insights.

Copyright © 2013 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced orutilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by aninformation storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.(303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of theirrespective owners.

Page 3: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

© 2013 ITCourseware, LLC Rev 5.2.1 Page iii

Contents

Chapter 1 - Course Introduction ........................................................................................................... 11

Course Objectives .......................................................................................................................... 12Introduction .................................................................................................................................... 13Course Overview ........................................................................................................................... 14Using the Workbook ...................................................................................................................... 15Suggested References ..................................................................................................................... 16

Chapter 2 - Getting Started with Java .................................................................................................... 19

What is Java? ................................................................................................................................. 20How to Get Java ............................................................................................................................ 22A First Java Program ...................................................................................................................... 24Compiling and Interpreting Applications ........................................................................................... 26The JSDK Directory Structure ........................................................................................................ 28Labs ............................................................................................................................................... 30

Chapter 3 - Eclipse ............................................................................................................................... 33

Introduction to Eclipse .................................................................................................................... 34 Installing Eclipse ............................................................................................................................ 36Running Eclipse for the First Time .................................................................................................... 38Editors, Views, and Perspectives ..................................................................................................... 40Setting up a Project ........................................................................................................................ 42Creating a New Java Application .................................................................................................... 44Running a Java Application .............................................................................................................. 46Debugging a Java Application .......................................................................................................... 48Importing Existing Java Code into Eclipse ........................................................................................ 50

Chapter 4 - Datatypes and Variables ..................................................................................................... 53

Primitive Datatypes ......................................................................................................................... 54Declarations ................................................................................................................................... 56Variable Names .............................................................................................................................. 58Numeric Literals ............................................................................................................................. 60Character Literals ........................................................................................................................... 62String ............................................................................................................................................. 64

Page 4: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page iv Rev 5.2.1 © 2013 ITCourseware, LLC

String Literals ................................................................................................................................. 66Arrays ............................................................................................................................................ 68Non-Primitive Datatypes ................................................................................................................. 70The Dot Operator ........................................................................................................................... 72Labs ............................................................................................................................................... 74

Chapter 5 - Operators and Expressions ................................................................................................ 77

Expressions .................................................................................................................................... 78Assignment Operator ...................................................................................................................... 80Arithmetic Operators ...................................................................................................................... 82Relational Operators ....................................................................................................................... 84Logical Operators ........................................................................................................................... 86Increment and Decrement Operators ............................................................................................... 88Operate-Assign Operators (+=, etc.) .............................................................................................. 90The Conditional Operator ............................................................................................................... 92Operator Precedence ..................................................................................................................... 94Implicit Type Conversions ............................................................................................................... 96The Cast Operator ......................................................................................................................... 98Labs ............................................................................................................................................. 100

Chapter 6 - Control Flow ................................................................................................................... 103

Statements .................................................................................................................................... 104Conditional (if) Statements ............................................................................................................ 106Adding an else if ........................................................................................................................... 108Conditional (switch) Statements .................................................................................................... 110while and do-while Loops ............................................................................................................. 112for Loops ..................................................................................................................................... 114A for Loop Diagram ..................................................................................................................... 116Enhanced for Loop ....................................................................................................................... 118The continue Statement ................................................................................................................. 120The break Statement ..................................................................................................................... 122Labs ............................................................................................................................................. 124

Chapter 7 - Methods .......................................................................................................................... 127

Methods ....................................................................................................................................... 128Calling Methods ........................................................................................................................... 130Defining Methods ......................................................................................................................... 132Method Parameters ...................................................................................................................... 134

Page 5: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

© 2013 ITCourseware, LLC Rev 5.2.1 Page v

Scope .......................................................................................................................................... 136So, Why All the static? .................................................................................................................. 138Labs ............................................................................................................................................. 140

Chapter 8 - Object-Oriented Programming ......................................................................................... 143

Introduction to Object-Oriented Programming ............................................................................... 144Classes and Objects ..................................................................................................................... 146Fields and Methods ...................................................................................................................... 148Encapsulation ............................................................................................................................... 150Access Control ............................................................................................................................. 152Inheritance .................................................................................................................................... 154Polymorphism ............................................................................................................................... 156Best Practices ............................................................................................................................... 158Labs ............................................................................................................................................. 160

Chapter 9 - Objects and Classes ........................................................................................................ 163

Defining a Class ............................................................................................................................ 164Creating an Object ....................................................................................................................... 166Instance Data and Class Data ....................................................................................................... 168Methods ....................................................................................................................................... 170Constructors ................................................................................................................................. 172Access Modifiers .......................................................................................................................... 174Encapsulation ............................................................................................................................... 176Labs ............................................................................................................................................. 178

Chapter 10 - Using Java Objects ........................................................................................................ 181

Printing to the Console .................................................................................................................. 182printf Format Strings ..................................................................................................................... 184StringBuilder and StringBuffer ....................................................................................................... 186Methods and Messages ................................................................................................................ 188toString ........................................................................................................................................ 190Comparing and Identifying Objects ............................................................................................... 192Parameter Passing ........................................................................................................................ 194Destroying Objects ....................................................................................................................... 196The Primitive-Type Wrapper Classes ............................................................................................ 198Enumerated Types ........................................................................................................................ 200Labs ............................................................................................................................................. 202

Page 6: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page vi Rev 5.2.1 © 2013 ITCourseware, LLC

Chapter 11 - Inheritance in Java .......................................................................................................... 205

Inheritance .................................................................................................................................... 206Inheritance in Java ........................................................................................................................ 208Casting ......................................................................................................................................... 210Method Overriding ....................................................................................................................... 212Polymorphism ............................................................................................................................... 214super ............................................................................................................................................ 216The Object Class .......................................................................................................................... 218Labs ............................................................................................................................................. 220

Chapter 12 - Advanced Inheritance and Generics ................................................................................ 223

Abstract Classes ........................................................................................................................... 224Interfaces ..................................................................................................................................... 226Using Interfaces ............................................................................................................................ 228Collections ................................................................................................................................... 230Generics ....................................................................................................................................... 232Comparable ................................................................................................................................. 234Labs ............................................................................................................................................. 236

Chapter 13 - Packages ....................................................................................................................... 239

Packages ...................................................................................................................................... 240The import Statement .................................................................................................................... 242Static Imports ............................................................................................................................... 244CLASSPATH and Import ............................................................................................................. 246Defining Packages ........................................................................................................................ 248Package Scope ............................................................................................................................ 250Labs ............................................................................................................................................. 252

Chapter 14 - Exception Handling ........................................................................................................ 255

Exceptions Overview .................................................................................................................... 256Catching Exceptions ..................................................................................................................... 258The finally Block ........................................................................................................................... 260Exception Methods ....................................................................................................................... 262Declaring Exceptions .................................................................................................................... 264Defining and Throwing Exceptions ................................................................................................. 266Errors and RuntimeExceptions ...................................................................................................... 268Labs ............................................................................................................................................. 270

Page 7: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

© 2013 ITCourseware, LLC Rev 5.2.1 Page vii

Chapter 15 - Input/Output Streams ..................................................................................................... 273

Overview of Streams .................................................................................................................... 274Bytes vs. Characters ..................................................................................................................... 276Converting Byte Streams to Character Streams ............................................................................. 278File Object ................................................................................................................................... 280Binary Input and Output ................................................................................................................ 282PrintWriter Class .......................................................................................................................... 284Reading and Writing Objects ......................................................................................................... 286Closing Streams ............................................................................................................................ 288Labs ............................................................................................................................................. 290

Chapter 16 - Core Collection Classes ................................................................................................. 293

The Collections Framework .......................................................................................................... 294The Set Interface .......................................................................................................................... 296Set Implementation Classes ........................................................................................................... 298The List Interface .......................................................................................................................... 300List Implementation Classes .......................................................................................................... 302The Queue Interface ..................................................................................................................... 304Queue Implementation Classes ...................................................................................................... 306The Map Interface ........................................................................................................................ 308Map Implementation Classes ........................................................................................................ 310Labs ............................................................................................................................................. 312

Chapter 17 - Collection Sorting and Tuning ......................................................................................... 315

Sorting with Comparable .............................................................................................................. 316Sorting with Comparator ............................................................................................................... 318Sorting Lists and Arrays ................................................................................................................ 320Collections Utility Methods ........................................................................................................... 322Tuning ArrayList ........................................................................................................................... 324Tuning HashMap and HashSet ...................................................................................................... 326Labs ............................................................................................................................................. 328

Chapter 18 - Inner Classes ................................................................................................................. 331

Inner Classes ................................................................................................................................ 332Member Classes ........................................................................................................................... 334Local Classes ............................................................................................................................... 336Anonymous Classes ...................................................................................................................... 338

Page 8: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page viii Rev 5.2.1 © 2013 ITCourseware, LLC

Instance Initializers ........................................................................................................................ 340Static Nested Classes ................................................................................................................... 342Labs ............................................................................................................................................. 344

Chapter 19 - Introduction to Swing ..................................................................................................... 347

AWT and Swing ........................................................................................................................... 348Displaying a Window .................................................................................................................... 350GUI Programming in Java ............................................................................................................. 352Handling Events ............................................................................................................................ 354Arranging Components ................................................................................................................. 356A Scrollable Component ............................................................................................................... 358Configuring Components .............................................................................................................. 360Menus .......................................................................................................................................... 362Using the JFileChooser ................................................................................................................. 364Labs ............................................................................................................................................. 366

Chapter 20 - Introduction to JDBC ..................................................................................................... 369

The JDBC Connectivity Model ..................................................................................................... 370Database Programming ................................................................................................................. 372Connecting to the Database .......................................................................................................... 374Creating a SQL Query .................................................................................................................. 376Getting the Results ........................................................................................................................ 378Updating Database Data ............................................................................................................... 380Finishing Up ................................................................................................................................. 382Labs ............................................................................................................................................. 384

Appendix A - JDBC SQL Programming .............................................................................................. 387

Error Checking and the SQLException Class ................................................................................ 388The SQLWarning Class ................................................................................................................ 390JDBC Types ................................................................................................................................. 392Executing SQL Queries ................................................................................................................. 394ResultSetMetaData ....................................................................................................................... 396Executing SQL Updates ................................................................................................................ 398Using a PreparedStatement ........................................................................................................... 400Parameterized Statements ............................................................................................................. 402Stored Procedures ........................................................................................................................ 404Transaction Management .............................................................................................................. 406Labs ............................................................................................................................................. 408

Page 9: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

© 2013 ITCourseware, LLC Rev 5.2.1 Page ix

Appendix B - Introduction to Threads ................................................................................................. 411

Non-Threaded Applications .......................................................................................................... 412Threaded Applications .................................................................................................................. 414Creating Threads .......................................................................................................................... 416Thread States ............................................................................................................................... 418Runnable Threads ......................................................................................................................... 420Coordinating Threads ................................................................................................................... 422Interrupting Threads ...................................................................................................................... 424Runnable Interface ........................................................................................................................ 426Labs ............................................................................................................................................. 428

Appendix C - Java EE Overview ........................................................................................................ 431

Introduction to Java EE ................................................................................................................. 432Java SE Building Blocks ............................................................................................................... 434Web Applications ......................................................................................................................... 436Web Services ............................................................................................................................... 438Enterprise JavaBeans .................................................................................................................... 440Additional Java EE APIs ............................................................................................................... 442POJO, Dependency Injection, and Annotations ............................................................................. 444The Java EE Platform ................................................................................................................... 446

Appendix D - Eclipse Shortcuts .......................................................................................................... 449

Shortcut Key Sequences ............................................................................................................... 450More Shortcut Key Sequences ..................................................................................................... 452

Index .................................................................................................................................................. 455

Page 10: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page x Rev 5.2.1 © 2013 ITCourseware, LLC

Page 11: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 11

Chapter 1 - Course Introduction

Page 12: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Page 12 Rev 5.2.1 © 2013 ITCourseware, LLC

Java Fundamentals for Non-C Programmers

Write stand-alone applications using the Java language.

Accurately implement Object-Oriented concepts using Java features such asclasses, interfaces and references.

Create well-scoped classes using packages and inner classes.

Write programs which both handle and create exceptions.

Read and write data using input and output streams.

Use the Java Collections Framework to work with groups of objects.

Use the java.awt and javax.swing packages to create GUI applications.

Write Java programs that interface with databases via JDBC.

Course Objectives

Page 13: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 13

Introduction

Most Java textbooks and training materials assume that the student is a proficient C, C++ or C#programmer. This allows the author to bypass the basic, low-level syntax that actually gets all the workdone, and focus on higher-level aspects of class design and the use of Java APIs. This leaves non-Cprogrammers to learn the syntax and semantics of the actual Java language entirely on their own, while at thesame time trying to pick up the higher-level concepts.

The purpose of this course is to completely present, explain, and exercise the basic syntax of Java toprogrammers without a C/C++/C# background. The designers of the Java programming languageborrowed heavily from the C language for basic constructs and syntax. This course covers, in depth, thoseparts of Java that would look familiar to a C programmer.

The C++ language is also derived from the C language, so it shares most of its basic syntax with C andJava. Variables, expressions and control flow will look very similar in all three of these languages. C++, likeJava, implements an object-oriented programming paradigm. However, C++ and Java implement object-oriented concepts in very different ways.

Page 14: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Page 14 Rev 5.2.1 © 2013 ITCourseware, LLC

Java Fundamentals for Non-C Programmers

Audience: This course is designed for programmers who want to moveinto the Java language, but have no C, C++, or C# background.

Prerequisites: This course assumes that the student is an experiencedprofessional programmer learning Java.

Classroom Environment:

A Java development workstation per student.

Course Overview

Page 15: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 15

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

Page 16: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Page 16 Rev 5.2.1 © 2013 ITCourseware, LLC

Java Fundamentals for Non-C Programmers

Arnold, Ken, James Gosling, and David Holmes. 2013. The Java Programming Language (5thEdition). Addison-Wesley, Reading, MA. ISBN 978-0132761680.

Bloch, Joshua. 2008. Effective Java (2nd Edition). Addison-Wesley, Reading, MA. ISBN 978-0321356680.

Cadenhead, Rogers. 2012. Sams Teach Yourself Java in 21 Days (6th Edition). Sams, Indianapolis,IN. ISBN 978-0672335747.

Eckel, Bruce. 2006. Thinking in Java (4th Edition). Prentice Hall PTR, Upper Saddle River, NJ. ISBN 978-0131872486.

Horstmann, Cay and Gary Cornell. 2012. Core Java 2, Volume I: Fundamentals (9th Edition).Prentice Hall PTR, Upper Saddle River, NJ. ISBN 978-0137081899.

Horstmann, Cay and Gary Cornell. 2013. Core Java 2, Volume II: Advanced Features (9th Edition).Prentice Hall PTR, Upper Saddle River, NJ. ISBN 978-0137081608.

Schildt, Herbert. 2011. Java, A Beginner's Guide (5th Edition). McGraw Hill, New York, NY.ISBN 978-0071606325.

Schildt, Herbert. 2011. Java The Complete Reference (8th Edition). McGraw Hill, New York, NY.ISBN 978-0070435926.

Sierra, Kathy and Bert Bates. 2005. Head First Java (2nd Edition). O'Reilly & Associates,Sebastopol, CA. ISBN 978-0596009205.

http://stackoverflow.com/questions/tagged/javahttp://www.javaworld.comhttp://www.javaranch.comhttp://www.oracle.com/technetwork/java

Suggested References

Page 17: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Course IntroductionChapter 1

© 2013 ITCourseware, LLC Rev 5.2.1 Page 17

Page 18: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Page 18 Rev 5.2.1 © 2013 ITCourseware, LLC

Java Fundamentals for Non-C Programmers

Page 19: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 19

Chapter 2 - Getting Started with Java

Objectives

Define Java terms such as JRE,JSDK, and JVM

Write, compile, and run a Javaprogram.

Page 20: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 20 Rev 5.2.1 ©2013 ITCourseware, LLC

Java is an Object-Oriented Programming language with extensive class libraries.

You need a Java Runtime Environment (JRE), consisting of a Java VirtualMachine (VM) and a copy of the Java API libraries, to run a Javaprogram.

You need the Java Software Development Kit (JSDK), including a JavaVM, a copy of the Java API libraries, and a Java compiler, to create a Javaprogram.

Write Once, Run Anywhere.

Code written on any platform, with any Java compiler, can be run on anyplatform with any Java Virtual Machine (interpreter).

Java borrowed the best of several programming languages, including C++, C#,Objective C, Cedar/Mesa, Smalltalk, Eiffel, and Perl.

What is Java?

Page 21: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 21

The Java white paper lists several design goals:

Simple — The language syntax is familiar, very much like C and C++, but many of the really nasty thingshave been removed.

Secure — Compile time and runtime support for security.

Distributed — The Java API library includes the java.net package.

Object-Oriented — Designed from the beginning to be strictly object-oriented. The Java API librariesinclude a large number of classes arranged in packages (like class libraries). There are no functions or globaldata outside of classes, e.g., main() or C++ friend functions.

Robust — Strongly typed — stronger type checking than C++. Compile-time checking for typemismatches. Simplified memory management. No pointers. Exception handling.

Portable — Java code is compiled into architecture-neutral bytecode. No implementation-dependentaspects in the language (e.g., the int type is 32 bits regardless of the platform word size).

Interpreted — The bytecode is interpreted on any platform that implements the Java Virtual Machine.

Multithreaded — Language and library support for multiple threads of control.

Dynamic — Classes are loaded as needed, locally or across the net. Runtime type information is built in.

High performance — Interpreted, so not as fast as C in execution speed. Just In Time (JIT) compilersmake Java programs almost as fast as C. Automatic Garbage Collection helps ensure needed memory isavailable.

Page 22: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 22 Rev 5.2.1 ©2013 ITCourseware, LLC

You can download the Java Software Development Kit for free from Oracle.

Oracle has ports for Solaris, Windows, OS X, and Linux platforms, andpublishes links to other ports.

The Oracle Java web site has many other resources, including the JSDKdocumentation, many demo programs, the FAQ, Java language spec, thewhite paper, etc.

Open source development environments like NetBeans and Eclipse are freelyavailable for download.

How to Get Java

Page 23: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 23

Page 24: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 24 Rev 5.2.1 ©2013 ITCourseware, LLC

Hands On:

Type the following program into a text editor:

package examples;

public class Hello { public static void main(String[] args) { System.out.print("Hello, "); if (args.length == 0) System.out.println("World!"); else System.out.println(args[0] + "!"); }}

We are defining a top-level class named Hello.

The name of the file must be ClassName.java; e.g., Hello.java.

Case is important.

The file should reside in a directory that corresponds to the package name.

A First Java Program

Page 25: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 25

The classic first program in Java is just "Hello, World!":

examples/HelloWorld.javapackage examples;

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }}

Ours is very similar, but a little more interesting.

Page 26: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 26 Rev 5.2.1 ©2013 ITCourseware, LLC

The steps to compile and interpret a Java application:

1. Create the source file with a text editor.

2. Compile the source into bytecode:

javac examples\Hello.java

3. Interpret the bytecode:

java examples/Hello

or

java examples/Hello Bob

Compiling and Interpreting Applications

Page 27: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 27

public class Hello public static void System.out.print(" if (args.length == System.out.prin else

examples\Hello.java

feca beba 0300 2d000007 071a 1b00 0007 0a0005 0a0a 0300 0b00 001700 000c 001f 010d 034c28 616a 6176 6c2f 6e676e 293b 0156 1600 5b

examples\Hello.class

1. Load bytecode from the file Hello.class

Class Hello public void main()

2. Interpret and run bytecode:

Hello.main("Bob")

Java VM

javac examples\Hello.java

java examples/Hello Bob

Environment Variables

The easiest way to run java and javac is to have their location in your PATH environment variable.

On Linux:PATH=$PATH:/JAVA_HOME/bin

On Windows:PATH=%PATH%;c:\JAVA_HOME\bin

Where JAVA_HOME is your Java installation directory.

Stand-alone Applications

Java programs can run as stand-alone applications. They can be started from a DOS or Linux prompt. On aWindows platform, or a graphical Linux platform, you can run a Java program that has a graphical userinterface from an icon on your desktop.

Page 28: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 28 Rev 5.2.1 ©2013 ITCourseware, LLC

Java should be installed in some globally-accessible directory, such as/usr/local/java or C:\Program Files\Java.

src.zip is an archive which contains all of the source code for the standardJava library classes; this can be expanded to view the source code.

bin/ contains the javac compiler and the java interpreter, among other tools;this directory needs to be in your PATH environment variable.

lib/ contains Java Archive (JAR) files used by the Java tools.

jre/ contains subdirectories with files for the Java Runtime Environment.

jre/bin/ contains copies of the tools used at runtime and libraries that theyuse.

jre/lib/ contains resource files for fonts, etc., and the standard Java libraryclassfiles (in rt.jar).

include/ contains C header files for use with the Java Native Interface.

The JSDK Directory Structure

Page 29: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 29

Oracle provides several Java tools with the JSDK. Here a few of the ones used most:

javac — the source code compiler.

javac produces architecture-neutral “bytecode.” The compiler produces a bytecode fileClassname.class; e.g., javac HelloWorld.java produces HelloWorld.class.

java — the bytecode interpreter.

The “virtual machine” (java) interprets bytecode for specific architectures. This is how stand-alone(non-applet) Java programs are executed.

java Classname

e.g.,

java HelloWorld

Do not include the .class extension.

appletviewer — a mini-browser for testing applets.

appletviewer reads an HTML file containing an <applet ...> tag, and loads and runs that appletclass file.

javap — a “disassembler” for bytecode.

jdb — the bytecode debugger.

javadoc — a utility to generate .html files which document the methods and hierarchy of your classes. Forjavadoc to work, you must:

1. Add javadoc comments to your .java file:

/** This is a Javadoc comment */

2. Run javadoc on your .java file:

javadoc HelloWorld.java

jar — a utility to create JAR files (similar to ZIP files).

Page 30: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 30 Rev 5.2.1 ©2013 ITCourseware, LLC

Write a Java application called MyName that prints out your name, and compile it usingjavac. List your directory. What was created? Run your program.(Solutions: MyName.java)

What happens if the name of the .java file is different from the class name contained in it?Copy MyName.java to Name.java. What messages do you get from the compiler?(Solution: Name.txt)

Try disassembling one of your .class files with javap -c (leave off the .class extension). Tryjavap -help.(Solution: MyName_javap_output)

Labs

Page 31: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Getting Started with JavaChapter 2

© 2013 ITCourseware, LLC Rev 5.2.1 Page 31

Page 32: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 32 Rev 5.2.1 ©2013 ITCourseware, LLC

Page 33: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 33

Chapter 3 - Eclipse

Objectives

Install and configure Eclipse.

Create and manage Java projects.

Write, compile, run, and debug Javaprograms in Eclipse.

Page 34: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 34 Rev 5.2.1 © 2013 ITCourseware, LLC

Eclipse is the most popular Java Integrated Development Environment (IDE)available today.

It is freely available for download from the Eclipse Foundation.

IBM started the Eclipse project in April of 1999 with the goal of "eclipsing" thedominance of Microsoft Visual Studio within the integrated developmentenvironment (IDE) space.

IBM donated the initial Eclipse code base to the open source communityin November of 2001 — just one month after version 1.0 was released.

Eclipse has become much more than a pure Java, open source IDE; it is aframework on which companies can develop their own tools.

Users can combine tools from different vendors to accomplish their goals.

The Eclipse Project is made up of multiple sub-projects, including:

The Eclipse Platform is the core IDE that most people associate with theterm "Eclipse."

It is extensible: you can plug-in tools from various vendors tocustomize it to your needs.

The Java Development Tools (JDT) project provides the necessary plug-ins to support development of Java applications.

These tools include the incremental compiler, the debugger, and theeditor.

The Plug-in Development Environment (PDE) project provides tools thatallow you to build your own plug-ins for Eclipse.

Introduction to Eclipse

Page 35: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 35

Eclipse has had numerous releases since its inception:

Eclipse 1.0 — October, 2001Eclipse 2.0 — June, 2002Eclipse 3.0 — June, 2004Eclipse 3.1 — June, 2005Eclipse 3.2 (Callisto) — June, 2006Eclipse 3.3 (Europa) — June, 2007Eclipse 3.4 (Ganymede) — June, 2008Eclipse 3.5 (Galileo) — June, 2009Eclipse 3.6 (Helios) — June, 2010Eclipse 3.7 (Indigo) — June, 2011Eclipse 4.2 (Juno) — June, 2012Eclipse 4.3 (Kepler) — June, 2013

Page 36: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 36 Rev 5.2.1 © 2013 ITCourseware, LLC

Download the most recent Eclipse release build from http://www.eclipse.org/downloads/.

You will find versions supporting Windows, Linux, and Mac OS X.

The file you download will be a .zip file (or tar.gz), rather than an installprogram.

The download does not include a Java Runtime Environment.

You must install a Java 6 or newer JRE for Eclipse to work.

You do not need the full Java Software Development Kit unless youwant to be able to step through the library source code duringdebug.

Extract the downloaded file to your local drive.

An eclipse directory will be created with several subdirectories.

That is all there is to it — you have successfully downloaded and installedEclipse!

Installing Eclipse

Page 37: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 37

Page 38: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 38 Rev 5.2.1 © 2013 ITCourseware, LLC

Run the Eclipse executable to start the Eclipse IDE.

The executable is found in the eclipse directory and is called eclipse.exeon Windows and eclipse on Linux.

Eclipse will use the first Java VM it finds in your PATH when it runs.

To explicitly set the VM, pass the -vm argument to the Eclipseexecutable:

eclipse -vm c:\jre\bin\javaw.exe

The first time you run Eclipse, it will ask you to select a workspace location.

A workspace is a directory where your projects will be stored.

This value can be passed in on the command-line with the -dataargument:

eclipse -data c:\code\myworkspace

After you have selected a workspace, you will see a welcome screen thatprovides links to tutorials, sample applications, overview topics, andinformation on what's new in the current version of Eclipse.

You can skip this introductory content by choosing the Workbench linkon the right of the screen or by clicking the x next to the word Welcome inthe upper left corner of the screen.

To get back to the welcome screen in the future, you can choose theHelp Welcome menu item.

Running Eclipse for the First Time

Page 39: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 39

For more command-line options, see:http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fruntime-options.html

Click here to switchto the workbench.

Page 40: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 40 Rev 5.2.1 © 2013 ITCourseware, LLC

You use an editor to enter text into Eclipse.

The JDT Java Editor provides syntax coloring, code completion, and codeformatting, among other things.

A simple text editor is also included as part of the Eclipse Platform.

Other editors, such as an HTML editor, can be added as plug-ins.

Multiple editors can be open at once and they will appear as stackedinstances with individual tabs for selection.

Views display information about an object; they typically supplement the datathat is visible in the current editor.

The JDT provides a Package Explorer View and Outline View, among others.

Display additonal views by choosing Window Show View.

Perspectives are combinations of editors and views arranged in the workbench.

You can switch from one perspective to another to see the appropriatecombination of views and editors for your current needs by choosingWindow Open Perspective.

The Window menu also allows you to save, customize, reset, and closePerspectives.

The Java Perspective is the default perspective that you will see afterdismissing the welcome screen.

Editors, Views, and Perspectives

Page 41: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 41

Page 42: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 42 Rev 5.2.1 © 2013 ITCourseware, LLC

Before you can edit any Java code, you must first create a project.

A project is a group of packages.

You can have one default package per project, at most.

You can find the .java files that correspond to the code you are editingwithin your workspace directory.

To create a new project, choose File New Java Project.

Enter a project name into the Project Name text box.

The project name will become a subdirectory within yourworkspace directory.

You can also specify which version of Java your project should becompliant with.

Click Finish to create the project.

Once your project has been created, you will see the project name listed in thePackage Explorer view.

Setting up a Project

Page 43: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 43

Page 44: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 44 Rev 5.2.1 © 2013 ITCourseware, LLC

To create a Java class, click on File New Class.

You can enter the name of the package to which your new class shouldbelong.

You must specify a name for the new class in the Name text field.

Check the appropriate radio button and checkboxes to apply theappropriate modifiers to the new class.

Eclipse can also automatically generate the main() method for you.

Click Finish to create the new class.

The new class will automatically open up in a Java editor where you can addyour code to the class.

Every time you save the file, Eclipse will compile your class for you.

Any compiler errors are visible in the Problems view at the bottom of thescreen.

Creating a New Java Application

Page 45: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 45

Look for compilererrors here.

Page 46: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 46 Rev 5.2.1 © 2013 ITCourseware, LLC

To run your program, click the Run button in the toolbar.

The results will be displayed in the Console view at the bottom of thescreen.

If you would like to run your program with custom options, choose Run RunConfigurations.

Choose Java Application and click the New button.

Use the Arguments tab to pass in arguments and various other tabs tocustomize the environment before you invoke the program.

Click the Run button to execute your program.

Running a Java Application

Page 47: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 47

Standard outand standard

err are shown inthe console.

This is the Run button.

Page 48: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 48 Rev 5.2.1 © 2013 ITCourseware, LLC

Before debugging your program, set at least one breakpoint by double-clickingon the blue margin of the Java editor to the left of the line of code where youwish to set the breakpoint.

Click the Debug button in the toolbar.

You will be notified that the perspective will change to the debugperspective before the debugger starts.

Within the debug perspective, you are presented with multiple views and adifferent toolbar.

Use the toolbar buttons to step through the program as it runs.

The Debug view displays the current location within the method call stack.

The Variables view shows you the current value of the variables in yourprogram.

You can also hover your mouse over any variable reference in theEditor to see its current value.

The Breakpoints view allows you to manage the breakpoints in yourdebug session.

The Console view displays the current results that have been written tostandard out.

The Outline view displays the structure of your class and highlights thecurrent method you have stepped into.

After you have completed debugging your program, switch back to the JavaPerspective by clicking Window Open Perspective Java or you can clickthe Java button in the upper right corner of the screen.

Debugging a Java Application

Page 49: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 49

Note:If you have installed a JSDK rather than a JRE, Eclipse can step into the source code for the Java APIlibraries.

Use this toolbar to stepthrough your application.

Page 50: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 50 Rev 5.2.1 © 2013 ITCourseware, LLC

Importing Existing Java Code into Eclipse

To load pre-existing Java files into an Eclipse project, use the Import feature bychoosing File Import...

Choose General File System to tell Eclipse to look on your local drivesfor the existing Java files.

Browse to the directory above where your packages are located.

Choose the checkboxes for the packages to import into your project.

Make sure the Into folder text field specifies the name of the workspacefolder within your project you wish to import into.

Click Finish.

You can also copy the files into the workspace folder using your file system'scopy utilities.

Choose File Refresh and the files will be automatically imported intoyour project.

On Windows systems, you can even drag the files from your file system into anEclipse project.

To load existing Eclipse projects into your workspace, chooseFile Import... General Existing Projects into Workspace and select either theroot directory or archive file to load the projects from.

Page 51: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 3 Eclipse

© 2013 ITCourseware, LLC Rev 5.2.1 Page 51

Try It:Load the pre-created Eclipse projects for this course into your Eclipse workspace using the Import wizard.First, click on File Import General Existing Projects into Workspace. Next, choose the Selectarchive file radio button and browse to the location of the student zip file (ask your instructor where this zipfile is located). Click on Finish. You should see a project for each chapter loaded into your workspace.

Page 52: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 143

Chapter 8 - Object-Oriented Programming

Objectives

Describe the most important features ofObject-Oriented Programming.

Define encapsulation, inheritance, andpolymorphism.

Understand the difference between anobject and a class.

List several Object-Oriented bestpractices.

Page 53: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 144 Rev 5.2.1 © 2013 ITCourseware, LLC

The goal of Object-Oriented Programming is to make the creation of large-scalesoftware applications easier and more maintainable.

Modular program design was introduced to break down the functionality of acomplex application into more manageable units.

Difficult and/or repeated parts of an application were placed in a functionto be called from other parts of the code.

The inner workings of the function were abstracted away and replaced bya function name.

Object-oriented programming adds an additional level of abstraction bygrouping modules with related functionality together with the information thatthey manipulate.

This cohesive unit is called an object.

Software objects often represent real-world objects that contain both stateand behavior.

The state of the object is maintained by a set of variables inside theobject, known as fields.

The behavior of the object is performed by a set of functions insidethe object, known as methods.

Introduction to Object-Oriented Programming

Page 54: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 145

Page 55: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 146 Rev 5.2.1 © 2013 ITCourseware, LLC

Classes and Objects

A class defines the structure of an object; an analogy would be a blueprint of ahouse.

The blueprint defines the structure of the house, classes define thestructure and content of an object.

Some information and functionality exist in the class, and is shared by allinstances of the class.

For example, the square footage of a house can be found on theblueprint.

An example of a class would be a date.

Dates maintain information (month, day, and year) plusfunctionality to access and manipulate that information.

An object is an instance of a class, just as a house is an instance of a blueprint.

Many houses can be built off of one blueprint and many objects can becreated from one class.

Each object will contain its own separate state; the state is maintained bythe variables contained in the object.

Examples of dates would be different objects that represented the currentdate, Christmas Day, New Year's Day, and so on.

Page 56: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 147

The following is a Unified Modeling Language (UML) Class Diagram for the Date class. There arethree sections to the diagram. The top section contains the class name, the second section lists the fields,and the last section contains the signatures of the various methods.

The next UML diagram depicts an actual object of the Date class. Notice the name of the object isunderlined to indicate that it is not a class, but an instance of the class. Additionally, each object fieldcontains values depicting the state of the Date object.

etaD

htnomyadraey

diov:)tni,tni,tni(tinidiov:)(yalpsiddiov:)tni(yaDtesdiov:)tni(htnoMtesdiov:)tni(raeYtes

tni:)(yaDtegtni:)(htnoMtegtni:)(raeYteg

etaD:dni

7=htnom4=yad

6771=raey

Page 57: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 148 Rev 5.2.1 © 2013 ITCourseware, LLC

Fields and Methods

A field is a data item that is defined in a class.

Fields can be divided into two different categories, static and instance.

Static fields reside in the class, just as the square footage of a houseresides on the blueprint for the house.

A static field is a piece of data that will exist even if no instances ofthe class have been created.

It will be shared by all objects of that class.

Instance fields reside in various objects of the class and each object willhave its own copy of its fields.

The current Date object will contain today's date, theIndependence Day object will contain 7/4/1776, and so on.

A method is a function that is declared inside of a class.

Methods are sometimes referred to as member functions.

Methods provide the functionality of the object.

Calling a method on an object can also be seen as asking the object toperform a needed task.

You can also have both static and instance methods.

Page 58: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 149

A new static method has been added to the Date class that will create a new Date object representingthe current date. Notice the currentDate() method is underlined to identify it as a static method, instead ofan instance method.

etaD

htnomyadraey

diov:)tni,tni,tni(tinidiov:)(yalpsiddiov:)tni(yaDtesdiov:)tni(htnoMtesdiov:)tni(raeYtes

tni:)(yaDtegtni:)(htnoMtegtni:)(raeYteg

etaD:)(etaDtnerruc

Page 59: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 150 Rev 5.2.1 © 2013 ITCourseware, LLC

Encapsulation

The definition of encapsulation is made up of two parts:

It combines fields and methods inside a class.

It hides fields and implementation behind publicly-available methods.

Encapsulation guarantees that the data inside an object is correct and consistent.

For example, the month data inside of a Date object should never be lessthan 1 or greater than 12.

Encapsulation provides a level of abstraction between the user of a class and thefields contained inside the class.

You do not need to understand how the fields inside the class arestructured, just which methods to call in order to change the object stateor perform a certain task.

For example, the state of the Date object could be kept in three integerfields, representing month, day, and year, or as a floating point numberrepresenting the number of seconds from a particular date.

You should not know, or care, how the information is stored in theDate object as long as you can manipulate or retrieve it by callingmethods on the object.

The callable methods on an object from outside of the object make up theobject's interface.

The implementation of the object can change without changing theinterface.

Page 60: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 151

methods

fields

Page 61: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 152 Rev 5.2.1 © 2013 ITCourseware, LLC

Access Control

Use access control modifiers to enforce encapsulation.

These modifiers control who has access to fields and methods inside yourclass.

All fields and methods will be assigned an access control modifier to determinetheir visibility.

There are three primary access control modifiers in Object-OrientedProgramming:

public — Any code anywhere has access to the data and/ormethods.

private — Only methods inside the class have access to the dataand/or method.

protected — Classes that inherit this class will have access to thedata and/or methods.

Due to encapsulation, any fields declared inside a class are given the privatemodifier.

The only mechanism to modify this data from outside the class is bymeans of method calls.

Occasionally you might have a constant field inside your class begiven public access control, since it cannot be modified.

Methods may be public, private, or protected depending on whether you wantthem to be called from outside the object or from within the object.

Page 62: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 153

Various programming languages treat access control differently:

Java's protected modifier allows classes in the same package access to the fields or methods.Java has an additional modifier that is strictly package scope..NET has an additional modifier that provides assembly scope.C++ allows you to assign visibility modifiers at the inheritance level.

The following UML diagram for the Date class adds symbols that represent the access control of the dataand methods. A hyphen (-) represents private scope, a plus sign (+) represents public scope, a pound sign(#) represents protected scope, and the tilde (~) represents package scope.

etaD

htnom-yad-raey-

diov:)tni,tni,tni(tini++ diov:)(yalpsid+ diov:)tni(yaDtes+ diov:)tni(htnoMtes+ diov:)tni(raeYtes+ tni:)(yaDteg+ tni:)(htnoMteg+ tni:)(raeYteg

Page 63: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 154 Rev 5.2.1 © 2013 ITCourseware, LLC

Inheritance

Inheritance allows you to build a new datatype using an existing one as thefoundation.

You can therefore avoid representing the same thing twice by movingcommon fields and methods that are shared by multiple classes to acommon base class.

With an existing class as a starting point, you can use inheritance to create a newclass.

The new class can take on additional fields and methods.

The new class can override the code of a particular method with newimplementation code.

The class you inherit from is known as the superclass and the new class isknown as the subclass. Other terminology:

Base class — Derived classParent class — Child classGeneralized class — Specialized class

An object that is created from a subclass is not only an instance of the subclass,but also of its superclass.

This creates an "is-a" relationship between the superclass and thesubclass.

A timestamp "is a" date.

A toaster "is an" appliance.

A jet "is an" airplane.

Page 64: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 155

The following example shows a UML diagram of a new class called TimeStamp. The arrow fromTimeStamp to the Date class indicates that TimeStamp inherits from Date. TimeStamp adds 3additional fields: hour, minute, and second. TimeStamp overrides the display() method of Date.

etaD

htnom-yad-raey-

diov:)tni,tni,tni(tini++ diov:)(yalpsid+ diov:)tni(yaDtes+ diov:)tni(htnoMtes+ diov:)tni(raeYtes+ tni:)(yaDteg+ tni:)(htnoMteg+ tni:)(raeYteg

pmatSemiT

ruoh-etunim-

diov:)tni,tni,tni,tni,tni(tini++ diov:)(yalpsid

Page 65: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 156 Rev 5.2.1 © 2013 ITCourseware, LLC

Polymorphism

When one class inherits from another class an "is-a" relationship is built.

The "is-a" relationship says that a subclass is actually an instance of thesuperclass with additional data and methods.

A variable of the superclass type can reference a subclass object becausethe subclass object "is-a" superclass object.

Many different subclasses can have "is-a" relationships with the samesuperclass.

If a superclass variable is referencing a subclass object the variable can onlyaccess the superclass part of that object, with one notable exception.

The subclass might override one or more methods declared in thesuperclass.

If the superclass variable calls a method that has been overridden, themethod in the subclass will be executed.

This is done using dynamic (runtime) binding, since the object that thevariable is referencing cannot be determined at compile time.

A call to an overridden method from a base class variable is polymorphic, sincethe type of the object referenced will determine which method is actuallyexecuted.

Page 66: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 157

The following class diagram adds an additional class definition called TimeStampZone. This new classadds an integer that represents the time zone and methods to retrieve and modify the time zone value. Theclass also overrides the display() method that was established in the Date class.

A Date variable can reference a Date object, a TimeStamp object, or a TimeStampZone object. If youcall the display() method from this variable, then the display() method of the appropriate object beingreferenced will be executed.

etaD

htnom-yad-raey-

diov:)tni,tni,tni(tini++ diov:)(yalpsid+ diov:)tni(yaDtes+ diov:)tni(htnoMtes+ diov:)tni(raeYtes+ tni:)(yaDteg+ tni:)(htnoMteg+ tni:)(raeYteg

pmatSemiT

ruoh-etunim-

diov:)tni,tni,tni,tni,tni(tini++ diov:)(yalpsid

enoZpmatSemiT

enoZemit-

diov:)tni(enoZemiTtes+tni:)(enoZemiTteg+

diov:)(yalpsid+

Page 67: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 158 Rev 5.2.1 © 2013 ITCourseware, LLC

Best Practices

The following is a list of practices that will help in the design and maintenanceof Object-Oriented projects.

Methods should have as few parameters as possible.

Methods should mostly use their own fields.

Objects should have a limited number of responsibilities and theirmethods should fulfill those responsibilities.

Fields that are not constants should be private.

Methods should be as private as possible.

Everything inside of the class should have a common purpose (HighCohesion).

Classes should rely on the functionality of other classes as little aspossible (Low Coupling).

High cohesion and low coupling are usually in conflict with one another, butgenerally, high cohesion is more important.

Page 68: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Chapter 8 Object-Oriented Programming

© 2013 ITCourseware, LLC Rev 5.2.1 Page 159

Page 69: Java Fundamentals for Non-C Programmers - … · Java Fundamentals for Non-C Programmers Core Java 2, Volume I: Fundamentals (9th Edition). Core Java 2, Volume II: Advanced Features

Java Fundamentals for Non-C Programmers

Page 160 Rev 5.2.1 © 2013 ITCourseware, LLC

Create a UML class diagram to represent a Person class. The class should include thefollowing fields: id, lastName, firstName, gender, and age. List a set of methods tomanipulate the values of these fields. There should also be a display() method. Be sure to addaccess control modifiers to the fields and methods.(Solution: person.gif)

Create a UML class diagram to represent an Employee class. The Employee class shouldinherit from the Person class created in the previous exercise. The Employee should extend thePerson class by adding a salary field and a department field. Again, add methods tomanipulate the additional fields. There should also be a static method called employeeCount()that returns an integer representing the number of employees created so far. TheemployeeCount() method should get its value from a static field called empCount. Be sure toadd your access control modifiers to the fields and methods.(Solution: employee.gif)

Create a UML class diagram to represent a Customer class. The Customer class shouldalso inherit from the Person class created in exercise . The Customer should add discountand balance fields. There should also be an additional static field calledreturningCustDiscount, representing a discount offered to all returning customers. Again, addmethods to manipulate the additional fields and the static field. Remember to add accesscontrol modifiers to the fields and methods.(Solution: customer.gif)

Labs