You are on page 1of 28

Introduction to Java

Slides adapted from Dr. Ramirez Confidential

Intro. to Object-Oriented Programming (OOP)


Object-Oriented Programming consists of 3 primary ideas:

Data Abstraction and Encapsulation


Operations on the data are considered to be part of the data type We can understand and use a data type without knowing all of its implementation details
Neither how the data is represented nor how the operations are implemented We just need to know the interface (or method headers) how to communicate with the object Compare to functional abstraction with methods

Confidential

Intro. to OOP
Inheritance
Properties of a data type can be passed down to a sub-type we can build
new types from old ones We can build class hierarchies with many levels of inheritance

Polymorphism
Operations used with a variable are based on the class of the object being accessed, not the class of the variable Parent type and sub-type objects can be accessed in a consistent way

Confidential

Objects and Data Abstraction

Consider primitive types

Each variable represents a single, simple data


value

Any operations that we perform on the data


are external to that data X+Y
Y X 10 5

+
Confidential

Objects and Data Abstraction


Consider the data

In many applications, data is more complicated than just a simple value Ex: A Polygon a sequence of connected points
The data here are actually:
int [] xpoints an array of x-coordinates int [] ypoints an array of y-coordinates int npoints the number of points actually in the Polygon

Note that individually the data are just ints


However, together they make up a Polygon

This is fundamental to object-oriented programming (OOP)

Confidential

Objects and Data Abstraction


Consider the operations

Now consider operations that a Polygon can do


Note how that is stated we are seeing what a Polygon CAN DO rather than WHAT CAN BE DONE to it This is another fundamental idea of OOP objects are ACTIVE rather than PASSIVE Ex:
void addPoint(int x, int y) add a new point to Polygon boolean contains(double x, double y) is point (x,y) within the boundaries of the Polygon void translate(int deltaX, int deltaY) move all points in the Polygon by deltaX and deltaY

Confidential

Objects and Data Abstraction

These operations are actually (logically) PART of the Polygon itself


int [] theXs = {0, 4, 4}; int [] theYs = {0, 0, 2}; int num = 2; Polygon P = new Polygon(theXs, theYs, num); P.addPoint(0, 2); if (P.contains(2, 1)) System.out.println(Inside P); else System.out.println(Outside P); P.translate(2, 3);
We are not passing the Polygon as an argument, we are calling the methods FROM the Polygon
Confidential

Objects and Data Abstraction


Objects enable us to combine the data and

operations of a type together into a single


entity P
Thus, the operations are always implicitly acting on the objects data Ex: translate means translate the points that make up P
xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate()

Confidential

Objects and Data Abstraction


For multiple objects of the same class, the

operations act on the object specified


int [] moreXs = {8, 11, 8}; int [] moreYs = {0, 2, 4}; Polygon P2 = new Polygon(moreXs, moreYs, 3);

P2

xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate()


Confidential

xpoints [8,11,8]] ypoints [0,2,4] npoints 3 addPoint() contains() translate()

Encapsulation and Data Abstraction


Recall that we previously discussed data abstraction

We do not need to know the implementation details of a data type in order to use it
This includes the methods AND the actual data representation of the object

This concept is exemplified through objects


We can think of an object as a container with data and operations inside
We can see some of the data and some of the operations, but others are kept hidden from us The ones we can see give us the functionality of the objects

Confidential

Encapsulation and Data Abstraction


As long as we know the method names, params P and how to use them, we dont need to know how the actual data is stored
Note that I can use a Polygon without knowing how the data is stored OR how the methods are implemented
I know it has points but I dont know how they are stored Data Abstraction!
Confidential

xpoints [0,4,4,0] ypoints [0,0,2,2] npoints 4 addPoint() contains() translate()

Composition & Inheritance


Sometimes we want to build a new class that is largely like one we already have

Much of the functionality we need is already there, but some things need to be added or changed
We can achieve this in object-oriented languages using one of two ways

Composition Inheritance

Confidential

Composition
We include an object of the class whose functionality we need as a private instance variable in our own class
public class NewClass { private OldClass oldVar;

Referred to as a has a relationship NewClass has an OldClass instance

We then write methods that wrap around similar methods of included class
public int foo(int arg) { return oldVar.foo(arg); }

The new class then seems to provide the same functionality as the included class In addition to any new functionality
Confidential

Composition
This is ideal when an object of NewClass isnt logically an object of OldClass
Fails the is a test

This is scheme is used by the input and output stream classes of the java.io package
Ex:
DataOutputStream out = new DataOutputStream(new FileOutputStream(file.out));

out stores the passed in FileOutputStream as an instance variable A FileOutputStream isnt necessarily a DataOutputStream, nor is a DataOutputStream necessarily a FileOutputStream Both are still output stream objects, though
Confidential

Inheritance
Alternatively, our NewClass can directly inherit the properties of OldClass
Just then need to add the new properties

Eliminates the need to redefine identical functionality in NewClass


The OldClass public interface can be access directly by the user

Can still augment the inherited interface Semantically defines a logical relationship between the two objects
Confidential

Inheritance and is a
We can understand this better by considering the is a idea
A subclass object is a superclass object However, some extra instance variables and methods may have been added and some other methods may have been changed

Note that is a is a one way operation


Subclass is a superclass (specific "is a" general)
With modifications / additions

Superclass is NOT a subclass (general not "is a" specific


Missing some properties

Ex: Bird is a Animal

Confidential

Inheritance and is a

Animal
is a is a Fish

is a

Bird

Human

Bird, Human and Fish are all Animals However, an Animal is not necessarily a Bird, Human or Fish
Confidential

Extending Classes

Inheritance in Java is implemented by extending a class


public class NewClass extends OldClass
{

We then continue the definition of NewClass as normal However, implicit in NewClass are all data and operations associated with OldClass
Even though we dont see them in the definition
Confidential

Inheritance Example
As another example

Compare MixedNumber class and MixedNumber2 class Both utilize the authors' RationalNumber class to do most of the "work" Both also have the same functionality, but MixedNumber uses composition and MixedNumber2 uses inheritance
Note simplicity of MixedNumber2 methods Read over the comments carefully! See RationalNumber.java, MixedNumber.java and MixedNumber2.java

Confidential

Java Class Hierarchy

In Java, class Object is the base class to all other classes

If we do not explicitly say extends in a new


class definition, it implicitly extends Object

The tree of classes that extend from Object


and all of its subclasses are is called the class hierarchy All classes eventually lead back up to Object This will enable consistent access of objects
Confidential

Polymorphism
Idea of polymorphism

See internet definition:


On Google type definition polymorphism and see the results
This search works for many CS terms that you may be curious about

http://www.wordiq.com/definition/Polymorphism_%28computer_science%29

Generally, it allows us to mix methods and


objects of different types in a consistent way

Confidential

Method Overloading
This is called ad hoc polymorphism, or method

overloading
In this case different methods within the same class or in a common hierarchy share the same name but have different method signatures (name + parameters)

public static float max(float a, float b)


public static float max(float a, float b, float c) public static int max(int a, int b)
When a method is called, the call signature is matched to the correct method version
Note: This is done during program COMPILATION

Confidential

Method Overloading
If an exact signature match is not possible, the one that is closest via widening of the values is used
Widening means that values of smaller types are cast into values of larger types Ex: int to long int to float float to double Fewer widenings provides a "closer" match

If two or more versions of the method are possible with the same amount of widening, the call is ambiguous, and a compilation error will result

See ex20.java Note: This type of polymorphism is not necessarily object-oriented can be done in non-object-oriented languages

Confidential

Polymorphism

Subclassing Polymorphism

Sometimes called true polymorphism


Consists basically of two ideas:

1) Method overriding
A method defined in a superclass is redefined in a subclass with an identical method signature Since the signatures are identical, rather than overloading the method, it is instead overriding the method
For subclass objects, the definition in the subclass replaces the version in the superclass

Confidential

Polymorphism
2) Dynamic (or late) binding

The code executed for a method call is associated with the


call during run-time The actual method executed is determined by the type of

the object, not the type of the reference

Allows superclass and subclass objects to be accessed in a regular, consistent way

Array or collection of superclass references can be used to


access a mixture of superclass and subclass objects This is very useful if we want access collections of mixed

data types (ex: draw different graphical objects using the Confidential

Polymorphism
Ex. Each subclass overrides the move() method in its own way Animal [] A = new Animal[3]; A[0] = new Bird(); A[1] = new Person(); A[2] = new Fish(); for (int i = 0; i < A.length; i++) A[i].move();

move()

move()

References are all the same, but objects are not


Method invoked is that associated with the OBJECT, NOT with the reference Confidential move()

Composition or Inheritance
Caveats like those we just discussed arise often with Inheritance Also, In heritance permanently associates a superclass with our class at compile time
We can only inherit from a single class Composition allows our class the flexibility to wrap around different superclasses at run-time

Composition is generally preferred over Inheritance We loose polymorphism and dynamic binding with Composition though
In many cases, we need those capabilities We use abstract classes and Interfaces to help solve these problems
Confidential

Features of Java
Java is simple Java is object-oriented

Java is distributed
Java is interpreted Java is robust Java is secure Java is architecture-neutral Java is portable Javas performance Java is multithreaded Java is dynamic
Confidential

You might also like