You are on page 1of 44

CSE/IT 213 - Review

New Mexico Tech


October 5, 2011

Procedural Programming
Attributes (data) and behaviors (methods = functions)
are normally separated

Code is placed into completely distinct functions/procedures/subrou


Black boxes inputs go in, outputs come out
Data is placed in separate structures
Data is manipulated by functions/ procedures/subroutines

Object Oriented Programming


(OOP)
Encapsulation: attributes and behaviors are contained
within a single entity (object)
Objects are responsible for manipulating their own data
Data hiding: access to certain attributes and methods
can be hidden from other objects
One object calls a method of (sends a message to)
another object that returns a result
The caller doesnt care how that data was obtained
2

What are objects?


The building blocks of object-oriented programming
Attributes: data representing the state of the object
Attributes are what differentiates objects
Instance fields
Behaviors: methods used to perform operations on data
What an object does
Invoked by sending a message to it
Specialized behaviors include setting and getting data

Object behaviors
Getters and setters support data hiding
Objects should not directly manipulate data within another object (encapsulation)
Provide controlled access to an objects data
e.g. private String name;
The
The
The
The

interface of a method is all a user needs to know


name of the method
parameters passed to the method
return type of the method
4

No class No object
Classes are blueprints, or templates, for making objects
Objects are instances of classes
Each object has its own copy of attributes and methods

Messages and Methods


Communication mechanism between objects
To instruct a class or an object to perform a task you
send a message only to the classes and objects that can
understand the message you sent to them.
A class or an object must possess a matching method
to be able to handle the received message.
A method defined for a class is called a class method,
and a method defined for an object is called an instance
method.
6

A value we pass to an object when sending a message


is called an argument of the message.
Access designations:public, protcted, and private

Encapsulation
The internal representation, the attributes and behaviors, of an object is hidden from all other objects. Only
the details pertinent to its use (i.e., interfaces) are accessible to other objects.
Class interfaces define the fundamental means of communication between objects
Each class design specifies interfaces for instantiation
(e.g., constructors) and operation (e.g., public methods) of objects
Any behavior of an object is invoked by a message sent
using a provided interface
7

Only public attributes and methods are considered the


interface
User should not see any part of the implementation
Why? Implementation can change and will not affect
users code

Inheritance
The abstraction of common attributes and behaviors
that allow the creation of a brand new class that will
inherit the attributes and methods of another class.
Common attributes and behaviors can be moved up to
a parent class (or superclass)
Superclass - contains all attributes and behaviors common to classes that inherit from it. Also known as a
parent class or generalization
Subclass - a specialization of the superclass with unique
attributes and behaviors. Inherits all attributes and behaviors from the superclass
8

Is-a relationships
A subclass is-a superclass.

Polymorphism
Each subclass may respond differently to the same message

Composition
We can create new objects by putting together other
objects
has-a relationship
9

UML
A graphical way to model class relationships
+ public methods
- private methods

10

Java
High level language
Java compiler produces bytecode - a machine language
for a virtual machine.
Why? portability. Bytecode should be able to run on
any machine without being recompiled.
Java Virtual Machine (JVM)
Interpreter that translates and executes the Java bytecode on an actual computer
11

User needs to install Java Runtime Environment (JRE)


on machine
Interpreter easier to write than a compiler.
Some issues with JVM performance and look and feel

Java Language
Know C know a a lot of Java
Flow-control, looping, arrays, variable declaration, data
types, operators similiar to C.
Use dot method to access the methods of an object (object.method(parameters)) similar to structure
member notation in C.
No pointers. You create references to objects with
the new keyword, but no memory management. The
garbage collector in java takes care of that.
12

import java.util.*; //this is not the same as \#include


class ClassName {
public static void main(String[] args) {
//only one main method in program
}
}

13

Classpath
The class path tells the Java SDK tools and applications where to find third-party and user-defined classes.

14

Numerical Data
Same basic data types as C - chars, ints, floats and
operators
Can do math using the Math class (square roots, powers,
trig, logs, etc).
Math is declared final.
allowed.

No inheritance of the class

15

Strings
No character arrays use a class called String
No need to worry about null terminator
There is a char type like C.

16

Date & Time


The epoch time in milliseconds since Jan 1. 1970 GMT.
Use GregorainCalendar class to manipulate data and
time data.

17

Console I/O
Use Scanner class to read in things from stdin.
To write to stdout use System.out.println("....");

18

Differences between C & Java


static
Instance variables or methods in a class may be declared
static.
Static variables and methods are associated with the
class not an object of the class.
Only a single copy of a static variable exists. Unlike
other instance variables which are copied to each new
object.
19

A static method is like a regular method that is defined


inside a class. Regular methods send messages to objects. There is no receiver object for static methods.
They operate on a class.
final keyword Instance variable, methods, and classes
can be declared final.
Final instance variables declares variable as a constant.
Set it and forget about it. Cannot change once set.
Final methods are methods that cannot be overridden.
No inherited class can redefine their meaning.
Final classes cannot be subclassed (i.e. inherited).

Equality of Objects
The == operator tests for object identity, not equality.
That is, do the objects point to the same object.
To test if two objects are equal use equals method.
Enhanced for loop
iterate over collections or arrays
for (varDeclartion : iterable)
statements;

Arrays
Slightly different syntax, put the subscript braces after
the data type and before the variable name.
String[] s not String s[]

20

Object Construction
a way to initialize objects (init instance variables)
If no defined constructors in your class, the default constructor for the parent class is used. A default constructor is one with no parameters. Even when you dont
extend a class explicitly, implicitly all classes inherit the
Object class, the mother-of-all classes.
There is an important difference between fields (instance variables) and local variables.
You must always explicitly initialize local variables in a
method.
21

But if you dont initialize a field in a class, it is automatically initialized to a default (0, false, or null) depending
on its type.
Once you write a constructor than there is no longer
a default constructor provided for you. You must write
your own.
Can overload constructors
Overloading occurs if several methods have the same
name but different parameters.

Parameter Names
Coming up with parameter names for constructor and
methods can be difficult/tedious. Single character parameters are not the best.
Parameters variables shadow instance variables with the
same name. That is, for the scope of the method the
local variable hides the name of the instance variable.
this is the implicit parameter. this refers to the current
object.
this is used to give parameter names the same name
as instance variables
22

private int myox;


public setMyox(int myox) {
this.myoxx = myox;
}
Besides referring to the current object, if this is the first
line in a constructor, then it calls another constructor
of the same class.
Another way to initialize instance variables, besides through
constructors or declarations, is to use an initialization
block.
An initialization block is an arbitrary block of code and
executed when the constructor is called.

Also there are static initializers


Order of initialization
1. All data fields are initialized to their default value
(0, false, or null).
2. All field initializers and initialization blocks are executed, in the order in which they occur in the class
declaration.
3. If the first line of the constructor calls a second
constructor, then the body of the second constructor
is executed.
4. The body of the constructor is executed.

Subclassing and Inheritance


Subclasses inherit instance variables (ivars) and methods from its super class
Can use methods and ivars as if they were declared in
the subclass.
To declare a class a subclass of another class use the
extends keyword

23

Overriding methods - polymorphism


Subclasses can define methods that have the exact
same signature as a method in a superclass.
The sublcass method is said to override the method of
the superclass.
Overriding replaces the implementation of the method.
This is called subtype polymorphism.
Use the optional keyword @override
24

When there are multiple implementations of a method


in the inheritance hierarchy of an object, the method
in the lowest class of the hierarchy always overrides all
others.
The most-derived method is the one that is executed.
This behavior holds even if we refer to the object through
a reference to its superclass
Advantage of polymorphism - you can write code for
objects that dont exist. When you write them just
make sure they inherit your parent class or extends your
parent class.

Constructors and Inheritance


Use the super keyword

25

Abstract Classes
use the abstract keyword
Give method names but no body, i.e. no implementation of the method.
This is called an interface.
Interfaces are implemented by classes.
If a class implements an interface it has to create the
bodies of the methods.
Also, if you want to use interfaces in a polymorphic
manner, i.e. use them as return and parameter types,
can use objects of classes that implement the interface.
No requirement that they share any ancestry.
26

Generic Array Lists


Gives you a list of any type of Object
ArrayList<Animal> animalFarm = new ArrayList<Animal>();
To sort an ArrayList of autoboxed objects or Strings
ArrayList implements List and List extends Collection
and the class Collections provide static utility methods
that operate on the class Collection.
Bottom line since ArrayList implements List can call
the sort method with an ArrayList
27

Sorting objects
static <T extends Comparable<? super T>>
void sort(List<T> list)
Sort is looking for objects of Type Comparable or its
subclass. (Just ignore <? super T> for the time being.
Comparable is an interface, how does it extend <T>? It
doesnt. In this context extends means implements and
<T extends Comparable> translates into T must be of a
type that implements Comparable.
The interface Comparable has only one method to implement.
28

int compareTo(T o)
Compares this object with the specified object for order.
Compares this object with the specified object for order.
Returns a negative integer, zero, or a positive integer as
this object is less than, equal to, or greater than the
specified object.
To sort objects have to add Comparable interface to the
class.

Collections and generics


Collections use generics to implment useful abstract
data structures ArrayList, Sets, etc.

29

Exceptions
try-catch blocks
exceptions versus errors

30

File I/O
Wrapper classes File provides access to file Streams
operate at byte level Use other classes to read and write
data DataInputStream for binary data;
textttBufferedInputStream for text processing.
Can also write objects to a file called serialization.

31

You might also like