introduction to object- oriented programming with java spring semester 2003 paul krause

31
Introduction to Introduction to Object-Oriented Object-Oriented Programming with Programming with Java Java Spring Semester 2003 Spring Semester 2003 Paul Krause Paul Krause

Post on 20-Dec-2015

224 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Introduction to Object-Introduction to Object-Oriented Programming Oriented Programming

with Javawith Java

Spring Semester 2003Spring Semester 2003

Paul KrausePaul Krause

Page 2: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Object-Orientation & JavaObject-Orientation & Java

ContentsContents Getting StartedGetting Started A Little Bit of SyntaxA Little Bit of Syntax Differences between C and JavaDifferences between C and Java Object-Oriented Programming in JavaObject-Oriented Programming in Java

Page 3: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Getting StartedGetting Started

Goto:Goto:http://java.sun.comhttp://java.sun.com

Download the Java Development Kit (JDK)Download the Java Development Kit (JDK) Its free!Its free!

Download the DocumentationDownload the Documentation Also free!Also free!

Buy Buy JAVA In a NutshellJAVA In a Nutshell, by David , by David Flanagan, Publ. O’RiellyFlanagan, Publ. O’Rielly It’ll cost you £19.95, sorry!It’ll cost you £19.95, sorry!

Page 4: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

File extensions in JavaFile extensions in Java

.java Source

Byte code.class

javac (compiler)

JVM Java Virtual Machine

Any Hardware (that supports the JVM)

Page 5: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

What you get in the JDKWhat you get in the JDK

appletviewerappletviewer For running AppletsFor running Applets

javacjavac Compiles .java Compiles .java .class .class

javajava Interprets a Java ClassInterprets a Java Class

classes.zipclasses.zip The system provided classesThe system provided classes

src.zipsrc.zip Complete source for standard Complete source for standard classesclasses

javadocjavadoc Generates Java HTML documentsGenerates Java HTML documents

javapjavap DisassemblerDisassembler

……

Page 6: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Object-Orientation & JavaObject-Orientation & Java

ContentsContents Getting StartedGetting Started A Little Bit of SyntaxA Little Bit of Syntax Differences between C and JavaDifferences between C and Java Object-Oriented Programming in JavaObject-Oriented Programming in Java

Page 7: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Defining a ClassDefining a Class

Account

numberbalance

credit_accountdebit_account

{membersfields

methods

public class Account {

public int number; public double balance;

public void credit(double x) {// do some sums } public void debit(double y) {// do checking then sums }}

Page 8: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

““Circle” ExampleCircle” Example

Circle

radius

circumferencearea

public class Circle {

}

public double radius;

public double circumference() { return 2 * PI * radius;}public double area() { return PI * radius * radius;}

public static final double PI = 3.14159;

Page 9: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

The “Circle” classThe “Circle” class

public class Circle {

// A class field public static final double PI= 3.14159; // A useful constant // A class method: just compute a value based on the arguments public static double radiansToDegrees(double rads) { return rads * 180 / PI; } // An instance field public double r; // The radius of the circle

// Two instance methods: they operate on the instance fields // of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference return 2 * PI * r; }}

Page 10: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

The “main” methodThe “main” method

public class Circle { public double r; // The radius of the circle public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference return 2 * PI * r; }

}

public static void main(String[] args) { int input = Integer.parseInt(args[0]); Circle c = new Circle(); c.r = input; double result = c.circumference(); System.out.println(result); }

Page 11: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Put “main” in a new class?Put “main” in a new class?

public class MakeCircle { public static void main(String[] args) {

int input = Integer.parseInt(args[0]);

Circle c = new Circle(); c.r = input; double circum = c.circumference(); System.out.println(circum); double a = c.area(); System.out.println(a);

}}

Page 12: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

An AssociationAn Association

MakeCircle

main

Circle

radius

circumferencearea

creates instances of

Page 13: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

File extensions in JavaFile extensions in Java

.java Source

Byte code.class

javac (compiler)

JVM Java Virtual Machine

Any Hardware (that supports the JVM)

Page 14: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

The Circle exampleThe Circle exampleC:\>cd Java

C:\Java>javac Circle.java

C:\Java>javac MakeCircle.java

C:\Java>java MakeCircle 4

25.1327250.26544

C:\Java>java MakeCircle 5

31.415978.53975

C:\Java contains Circle.java and MakeCircle.java

C:\Java now also contains Circle.class and MakeCircle.class

Page 15: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Object-Orientation & JavaObject-Orientation & Java

ContentsContents Getting StartedGetting Started A Little Bit of SyntaxA Little Bit of Syntax Differences between C and JavaDifferences between C and Java Object-Oriented Programming in JavaObject-Oriented Programming in Java

Page 16: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

DifferencesDifferences

No PreprocessorNo Preprocessor No analogues of No analogues of #define#define, , #include#include, , #ifdef#ifdef

Constants are replaced by Constants are replaced by static finalstatic final fieldsfields

No Global VariablesNo Global Variables Avoids possibility of namespace collisionsAvoids possibility of namespace collisions We will see later how you can make a We will see later how you can make a

constant or variable globally accessibleconstant or variable globally accessible

Page 17: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Java vs. CJava vs. C

Well-defined primitive type sizesWell-defined primitive type sizes Removes this as a platform dependencyRemoves this as a platform dependency

No pointersNo pointers Although Java Classes and Arrays are Although Java Classes and Arrays are

reference types, these references are reference types, these references are “opaque”. No “address of” or “dereference” “opaque”. No “address of” or “dereference” operatorsoperators

This is This is notnot a handicap and eliminates and a handicap and eliminates and important source of bugsimportant source of bugs

Page 18: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Java vs. CJava vs. C

Garbage CollectionGarbage Collection Objects are “tidied away” as soon as there are Objects are “tidied away” as soon as there are

no further references to themno further references to them So, no need to explicitly manage memorySo, no need to explicitly manage memory Eliminates memory leaksEliminates memory leaks

No goto statementNo goto statement Adds exception handling and labelled Adds exception handling and labelled breakbreak

and and continuecontinue statements statements

Page 19: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Java vs. CJava vs. C

Variable declarations anywhereVariable declarations anywhere Java allows local variable definitions to be Java allows local variable definitions to be

made anywhere in a method or blockmade anywhere in a method or block Good practice to group them, thoughGood practice to group them, though

Forward referencesForward references Methods can be invoked before they are Methods can be invoked before they are

defined (we’ll see why it is important to be defined (we’ll see why it is important to be able to do this)able to do this)

Page 20: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Java vs. CJava vs. C

Method overloadingMethod overloading Multiple methods can be defined with the same name, Multiple methods can be defined with the same name,

so long as they have different parameter listsso long as they have different parameter lists

No struct and union typesNo struct and union types No enumerated typesNo enumerated types No bitfieldsNo bitfields No typedefNo typedef No method pointersNo method pointers No variable-length argument listsNo variable-length argument lists

Page 21: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Object-Orientation & JavaObject-Orientation & Java

ContentsContents Getting StartedGetting Started A Little Bit of SyntaxA Little Bit of Syntax Differences between C and JavaDifferences between C and Java Object-Oriented Programming in JavaObject-Oriented Programming in Java

Page 22: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

The Members of a ClassThe Members of a Class

Class fieldsClass fields public static final double PI = 3.1416;public static final double PI = 3.1416;

Class methodsClass methods public static double public static double radiansToDegrees(double rads) {radiansToDegrees(double rads) {

… … }} Instance fieldsInstance fields

public double radius;public double radius; Instance methodsInstance methods

public double circumference() {…}public double circumference() {…}

Page 23: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Class FieldsClass Fields

public static final double PI = 3.14159public static final double PI = 3.14159

A field of type A field of type doubledouble Named Named PIPI (capitalise constants) (capitalise constants) Assigned a value of Assigned a value of 3.141593.14159 The The staticstatic modifier tags this as a Class modifier tags this as a Class

FieldField Associated with the class in which it is definedAssociated with the class in which it is defined

The The finalfinal modifier means it cannot be modifier means it cannot be changedchanged

Page 24: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Class Fields…Class Fields…

There is only one copy of There is only one copy of PIPI Any instance of Any instance of ClassClass can refer to this can refer to this

field as field as PIPI PIPI is essentially a Global Variable is essentially a Global Variable

BUTBUT Methods that are not part of Methods that are not part of CircleCircle

access this as access this as Circle.PICircle.PI No name collisionsNo name collisions

Page 25: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Class MethodsClass Methods

public static double radiansToDegrees(double public static double radiansToDegrees(double rads) {rads) {

return rads * 180 / PI;return rads * 180 / PI; }}

Single parameter of type Single parameter of type doubledouble and and returns a value of type returns a value of type doubledouble

Is essentially a “global method”Is essentially a “global method”// how many degrees is 2.0 radians?// how many degrees is 2.0 radians?double d = double d = Circle.radiansToDegrees(2.0);Circle.radiansToDegrees(2.0);

Page 26: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Instance FieldsInstance Fields

public double radius;public double radius; Each Each CircleCircle object can have a have a radius object can have a have a radius

independent of other independent of other CircleCircle objects objects Outside a class, a reference to an instance field Outside a class, a reference to an instance field

must be prepended by a reference to the must be prepended by a reference to the objectobject that contains itthat contains itCircle c = new Circle();Circle c = new Circle();c.radius = 2.0;c.radius = 2.0;Circle d = new Circle();Circle d = new Circle();d.radius = c.radius;d.radius = c.radius; Are they the same object?

Page 27: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Instance MethodsInstance Methods

Instance methods operate on Instance methods operate on instancesinstances of a of a Class, and not on the Class itselfClass, and not on the Class itself

E.g.E.g. area()area() circumference()circumference()

If an instance method is used from outside the If an instance method is used from outside the Class itself, it must be prepended by a reference Class itself, it must be prepended by a reference to the instance to be operated on:to the instance to be operated on: Circle c = new Circle();Circle c = new Circle(); c.radius = 2.0;c.radius = 2.0; double a = c.area();double a = c.area();

Page 28: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Creating an InstanceCreating an Instance

Every Class has at least one Every Class has at least one constructorconstructor This is used as a default constructor - a This is used as a default constructor - a

method with the same name as the Classmethod with the same name as the Class

Circle c = new Circle();Circle c = new Circle(); The The newnew operator creates a new operator creates a new

uninitialised instance of the Classuninitialised instance of the Class The constructor method is then called, The constructor method is then called,

with the new object passed implicitlywith the new object passed implicitly

Page 29: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Initialising an InstanceInitialising an Instance

A Constructor can use arguments placed A Constructor can use arguments placed between the parentheses to perform initialisationbetween the parentheses to perform initialisation

Define a new Constructor for CircleDefine a new Constructor for Circlepublic Circle(double r) {this.r = r;}public Circle(double r) {this.r = r;} Now two ways:Now two ways:Circle c = new Circle();Circle c = new Circle();

c.r = 0.25;c.r = 0.25; OrOrCircle c = new Circle(0.25);Circle c = new Circle(0.25);

Page 30: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Multiple ConstructorsMultiple Constructors

Public Circle() { r = 1.0; }Public Circle() { r = 1.0; }

Public Circle(double r) {this.r = r;}Public Circle(double r) {this.r = r;}

This is perfectly legalThis is perfectly legal Each constructor must have a different Each constructor must have a different

parameter listparameter list This is a simple example of This is a simple example of method method

overloadingoverloading

Page 31: Introduction to Object- Oriented Programming with Java Spring Semester 2003 Paul Krause

Destroying ObjectsDestroying Objects

Java automatically reclaims the memory Java automatically reclaims the memory occupied by an object when it is no longer occupied by an object when it is no longer neededneeded Garbage CollectionGarbage Collection

The Java interpreter can determine when The Java interpreter can determine when an object is no longer referred to by any an object is no longer referred to by any other object or variableother object or variable Also works for cyclesAlso works for cycles