Object-Oriented Programming
Benefits of Object Technology
Faster application development at a lower cost
Decreased maintenance time
Less complicated and faster customization
Higher quality code
What is Object-Oriented Programming?
A set of implementation techniques that: Can be done in any programming language May be very difficult to do in some programming languages A strong reflection of software engineering Abstract data types Information hiding (encapsulation) A way of encouraging code reuse Produces more malleable systems A way of keeping the programmer in touch with the problem Real world objects and actions match program objects and actions
Define
Object? a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. Class? a blueprint or prototype from which objects are created. Inheritance? inheritance provides a powerful and natural mechanism for organizing and structuring your software Interface? a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. Package? a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage
Objects
Objects are: Are building blocks for systems Contain data that can be used or modified
Bundle of variables and related methods
An object possesses: Identity A means of distinguishing it from other objects State What the object remembers Interface Messages the object responds to
Behavior What the object can do
Object Example
The car shown in the figure can be considered an object. It has an ID (1), state (its color, for instance, and other characteristics), an interface (a steering wheel and brakes, for example) and behavior (the way it responds when the steering wheel is turned or the brakes are applied). Many texts regard an object as possessing only two characteristics state and behavior. When considered this way, identity is part of the state, and the interface is included in the behavior.
Object Example
Dogs have: state (name, color, breed, hungry) behavior (barking, fetching, wagging tail). Bicycles also have: state (current gear, current pedal cadence, current speed) behavior (changing gear, changing pedal cadence, applying brakes).
Object Example
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation a fundamental principle of object-oriented programming.
By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.
Message and Object Communication
Objects communicate via messages
Messages in Java correspond to method calls (invocations)
Three components comprise a message: 1. The object to whom the message is addressed (Your Car) 2. The name of the method to perform (changeGears) 3. Any parameters needed by the method (lower gear)
sender
target
setSomething()
Object Messaging Example
By itself the car is incapable of activity. The car is only useful when it is interacted with by another object Object 1 sends a message to object 2 telling it to perform a certain action In other words, the driver presses the cars gas pedal to accelerate.
Accessing State
State information can be accessed two ways:
Using messages:
Eliminates the dependence on implementation Allows the developer to hide the details of the underlying implementation
Accessor messages are usually used instead of accessing state directly
Example: getSpeed() may simply access a state value called speed, or it could hide (or later be replaced by) a calculation to obtain the same value
Classes
A class Defines the characteristics and variables common to all objects of that class Objects of the same class are similar with respect to: Interface Behavior State Used to instantiate (create an instance of) specific objects Provide the ability of reusability Car manufacturers use the same blueprint to build many cars over and over
Class Example
The car at the top of the figure represents a class notice that the ID and color (and presumably other state details) are not known, but the interface and behavior are. Below the class car are two objects which provide concrete installations of the class
2
Class State Method
OO in Java
Language elements: Class-based object-oriented programming language with inheritance A class is a template that defines how an object will look and behave once instantiated
Java supports both instance and class (static) variables and methods
Nearly everything is an object They are accessed via references Their behavior can be exposed via public methods They are instantiated using the new construct
Java Classes
data members
method
public class Student { private int age; private String name; private Date birthDate; public int getAge() { return age; } }
class Student with data members and an instance method (Accessor)
Creating a New Project
All code in Eclipse needs to live under a project To create a project: File New Java Project
Creating a New Project (continued)
Enter a name for the project, then click Finish
Creating a New Project (continued)
The newly created project should then appear under the Package Explorer
The src folder
Eclipse automatically creates a folder to store your source code in called src
Creating a Class
To create a class, simply click on the New button, then select Class
Creating a Class (continued)
This brings up the new class wizard From here you can specify the following...
Package Class name Superclass Whether or not to include a main Etc
Fill in necessary information then click Finish to continue
The Created Class
As you can see a number of things have now happened
Directory structure for package and actual java file created automatically Source is loaded into the editor pane, already stubbed out
Source displayed in a hierarchical fashion listing each method name
Compiling Source Code
One huge feature of Eclipse is that it automatically compiles your code in the background This means that errors can be corrected when made
You no longer need to go to the command prompt and compile code directly
We all know that iterative development is the best approach to developing code, but going to shell to do a compile can interrupt the normal course of development This prevents going to compile and being surprised with 100+ errors
Example Compilation Error
This code contains a typo in the println statement
Packages/Classes with errors are marked with a red X
Position in file is marked with a red line 1 click allows you to jump to line with error Error underlined with red squiggly line (just like spelling errors in many word processors)
Methods with errors are marked with a red X
Often Eclipse may have suggestions on how to fix the problem if so, a small light bulb will be displayed next to the line of offending code
The Problems tab will contain a tabular representation of all errors across all files of all open projects
Example Compilation Error
When clicking on the light bulb, Eclipse suggests changing printn to either print or println
Running Code
An easy way to run code is to right click on the class and select Run As Java Application
Running Code (continued)
The output of running the code can be seen in the Console tab in the bottom pane
Run Configuration
Advanced options for executing a program can be found by right clicking the class then clicking Run As Run
Run Configuration (continued)
Here you can change/add any of the following:
JVM arguments Command line arguments Classpath settings Environment variables Which JVM to use
Re-Running Code
After you run the code a first time, you can re-run it just by selecting it from the run drop down menu
Debugging Code
Eclipse comes with a pretty good built-in debugger You can set break points in your code by double clicking in the left hand margin break points are represented by these blue bubbles
Debugging Code (continued)
An easy way to enter debug mode is to right click on the class and select Debug As Java Application
Debugging Code (Continued)
The first time you try to debug code you will be presented with the following dialog
Eclipse is asking if you want to switch to a perspective that is more suited for debugging, click Yes Eclipse has many perspectives based on what you are doing (by default we get the Java perspective)
Debug Perspective
These buttons allow you to step through the code
Note new Debug perspective click Java to return to normal
List of breakpoints
Variables in scope are listed here along with their current values (by right clicking you can change values of variables as you program is running)
This pane shows the current line of code we broke on Current high level location (class and method)
Output console, just like in normal run mode
Sampling of Some Other Features
Import organization Context assist Javadoc assist Getter/Setter generation Add unimplemented methods Exception handling Reminders Local history
Import Organization
Eclipse can automatically include import statements for any classes you are using, just press Control + Shift + o (letter o)
Import Organization (continued)
If the class is ambiguous (more than one in the API) then it will ask you to select the correct one
Import Organization (continued)
Import statements automatically included and organized
You can organize imports to clean them up at any time
Context Assist
If you are typing and press a . character and pause a second, Eclipse will show you a list of all available methods for the class
Prevents having to browse javadocs to see what methods are available Get context assist at any time by pressing Control + Space
Javadoc Assist
Eclipse can also help generate javadoc comments for you, simply place the cursor before the method and then type /** then Enter
Javadoc Assist (continued)
Eclipse will automatically generate a javadoc header for the method all stubbed out with the parameters, return type and exceptions
Getter/Setter Generation
Eclipse can automatically generate getters and setters for member of a class
Getter/Setter Generation (continued)
To generate getters and setters, right click in the main pane, then select Source Generate Getters and Setters
Getter/Setter Generation (continued)
Here you can selectively choose members for which to generate getters and setters
Getter/Setter Generation (continued)
Eclipse will then automatically generate the code for the getters and setters
Add Unimplemented Methods
Eclipse can also stub out methods that need to be present as a result of implementing an interface
Add Unimplemented Methods (continued)
You can use the quick fix light bulb to add the interfaces unimplemented methods to the class
Add Unimplemented Methods (continued)
Again Eclipse will go ahead and stub out the method for us
Exception Handling
Eclipse will also pickup on unhandled exceptions
Exception Handling (continued)
By clicking on the quick fix light bulb, Eclipse can suggest what to do to handle the exception
Exception Handling (continued)
Eclipse can automatically add a throws declaration to the method signature
Exception Handling (continued)
Alternately, Eclipse can also wrap the code inside a try/catch block
Tasks
Eclipse allows you to insert reminders into your code and stores them for you to come back and revisit them
Eclipse recognizes the following tags inside comments
TODO FIXME XXX
You can even add your own custom tasks through the preferences menu
Tasks (continued)
To add a table of all reminders in all of your source code you can add the Tasks view by clicking on Window Show View Tasks
Tasks (continued)
This neatly displays all tasks in a tabular form
Local History
Eclipse maintains a local history of file revisions which can be accessed by right clicking on the class, then selecting Compare With Local History
Local History (continued)
Previous saved revisions are displayed in the History pane, double click a revision to view in the built-in diff viewer
Hello world