Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java...

49
Tony Valderrama, SIPB IAP 2009

Transcript of Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java...

Page 1: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009

Page 2: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Review

• Summary of topics from Tuesday• Corrections

Review

Corrections• Brief example of interactive application

• Static imports• Compiling and executing from command lineCompiling and executing from command line• Class members

• More details about compiler/runtime environment• HistoryHistory• Places you’ll find Java• OOP!

AnnouncementsCourse website: http://stuff.mit.edu/iap/2009/java/Email: sipb-iap-java@mit eduEmail: sipb iap [email protected]

I need suggestions for advanced topics to cover next Thursday! (see website)

Page 3: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Arrays - correctionArrays correction

<type>[] name = new <type>[length];

int[] intArray = new int[10]; // 10 elements #0 9int[] intArray = new int[10]; // 10 elements, #0 - 9

String[] stringArray = new String[3]; // Objects work too.

stringArray.length; // 3intArray.length; // 10

NOTE: Java Arrays are first-class Objects, so initialized to null.

Images from The Java Tutorial

Page 4: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Arrays - correction

int[] intArray = new int[] { 1, 2, 3};int[][] intArray2 = new int[][] {{ 1, 2, 3, 4},

Arrays correction

y {{ }{ 5, 6, 7, 8},{ 9,10,11,12}};

intArray2 = new int[3][2]; // element arrays are now nullintArray2[0] = new int[1]; // element arrays can have different lengthsintArray2[0] = new int[1]; // element arrays can have different lengthsintArray2[0].length; // 1;

intArray2[1] = new int[1][]{2,3,4};

// efficient copying// (Object src, int srcPos, Object dest, int destPos, int length)System.arraycopy(intArray, 1, intArray2[1], 0, 2);System.arraycopy(intArray, 1, intArray2[1], 0, 2);intArray2[1][1]; // 3

Page 5: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Compiling - correctionCompiling correction

C:\$> javac Hello.java\$ j llC:\$> java Hello

Mmmmm... smell that coffee!

C:\$> javac tvald\intro2java\Hello.java\$ j \ j \ jC:\$> java tvald.intro2java.Hello

Mmmmm... smell that coffee!

Page 6: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Wake up and smell the coffee!

SoftwareJava Development Kit (JDK) - http://java.sun.com/javase/downloads/index.jsp

Wake up and smell the coffee!

Java Development Kit (JDK) http://java.sun.com/javase/downloads/index.jspEclipse Platform - http://www.eclipse.org/

ReferenceReferenceThe Java Tutorial - http://java.sun.com/docs/books/tutorial/index.htmlJava Language API - http://java.sun.com/javase/reference/api.jspJava SE Documentation - http://java sun com/javase/downloads/index jspJava SE Documentation http://java.sun.com/javase/downloads/index.jspJava SE Source Code - http://java.sun.com/javase/downloads/index.jsp

Page 7: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Not your daddy’s cup of Joe

There were five primary goals in the creation of the Java language:

Not your daddy s cup of Joe…

1) It should be "simple, object oriented, and familiar".2) It should be "robust and secure".3) It should be "architecture neutral and portable".3) It should be architecture neutral and portable .4) It should execute with "high performance".5) It should be "interpreted, threaded, and dynamic".

Java was designed to be safe, simple, and powerful.

Java whitedocs, as quoted in wikipedia

Page 8: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

From beans to brewFrom beans to brew

Images from the Java Tutorial

Page 9: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What’s in the cup?What s in the cup?

Images from the Java Tutorial

Page 10: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Ti liTimeline

Java 1.1Microsoft develops

own VM

James Goslingcreates Oak

Java 2 (v1.3.1)Hotspot VM

Java 5.0generics, optimizations,

support packages

Java 1.0goes public

Java 2 (v1.2)Java Foundation

Class (Swing)

Java 2 (v1.4.2)extensive support

packages

Java 6open source,optimizations

1991 1992 1994 1996 1998 2000 2003 2004 2005 2006 20071993 1995 1997 1999 2001 2002

Page 11: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Where you’ll find Java [incomplete list]

• Portable devices (cell phones, PDAs…)• UROPs

Where you ll find Java [incomplete list]

UROPs• Mars (NASA Rovers)• Eclipse• Banking appsBanking apps

Page 12: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

package tvald.intro2java;/*** This is a demo program.* @author tvald* @date 1/5/2009* @date 1/5/2009*/public class Hello {

public static void main(String[] args) {

System.out.println("Mmmm... Smell that coffee!"); // say hi

}

}

Page 13: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009

Page 14: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

A bit of philosophy

Plato5th-4th century B.C.

A bit of philosophy…

5 4 century B.C.Athens, Greece

...there is a form for every object or quality in reality: forms of dogs, human beings,...there is a form for every object or quality in reality: forms of dogs, human beings,mountains, colors, courage, love, and goodness. Form answers the question"what is that?" ...the object was essentially or "really" the Form and that thephenomena were mere shadows mimicking the Form; that is, momentary

t l f th F d diff t i t Th bl f i lportrayals of the Form under different circumstances. The problem of universals -how can one thing in general be many things in particular - was solved bypresuming that Form was a distinct singular thing but caused pluralrepresentations of itself in particular objects.p p j

http://en.wikipedia.org/wiki/Theory_of_Forms

Page 15: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

A bit of philosophy

Plato5th-4th century B.C.

A bit of philosophy…

5 4 century B.C.Athens, Greece

A Form is aspatial (outside the world) and atemporal (outside time). AtemporalA Form is aspatial (outside the world) and atemporal (outside time). Atemporalmeans that it does not exist within any time period. It did not start, there is noduration in time, and it will not end. It is neither eternal in the sense of existingforever or mortal, of limited duration. It exists outside time altogether. Forms are

ti l i th t th h ti l di i d th i t ti iaspatial in that they have no spatial dimensions, and thus no orientation in space,nor do they even (like the point) have a location… A Form is an objective"blueprint" of perfection.

http://en.wikipedia.org/wiki/Theory_of_Forms

Page 16: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is a Class?

A class is a blueprint or prototype from which objects are created.

What is a Class?

<modifiers> class name {

// members: fields, methods, constructors

}

Convention:

Class names begin with an uppercase letterClass names begin with an uppercase letterUse “camel case” - FirstSecondThird.Use only letters.

Page 17: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is a Class?What is a Class?

public class Hello {p {

public static String text;

public static void sayHi(){System out println("Mmmm Smell that " + text + "!")System.out.println("Mmmm... Smell that " + text + "!");

}

public static void main(String[] args) {text = "coffee";sayHi();

}

}

Page 18: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is an Object?What is an Object?

public class Hello {p {

String text;

public Hello(String s){text stext = s;

}

public void sayHi(){System.out.println("Mmmm... Smell that " + text + "!");

}

public static void main(String[] args) {Hello h = new Hello("coffee");h sayHi();h.sayHi();

}

}

Page 19: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is an Object?

An object is a software bundle of related state and behavior. Software objects are often

What is an Object?

used to model the real-world objects that you find in everyday life.

Software object

Image from The Java Tutorial

Page 20: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is an Object?

An object is a software bundle of related state and behavior. Software objects are often

What is an Object?

used to model the real-world objects that you find in everyday life.

Bicycle modeled as software object

Image from The Java Tutorial

Page 21: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

public class Bicycle {p y {

// the Bicycle class has two fieldspublic int gear;public int speed;

// the Bicycle class has one constructorpublic Bicycle(int startSpeed, int startGear) {

gear = startGear;speed = startSpeed;

}

// the Bicycle class has three methodspublic void setGear(int newValue) {

gear = newValue;gear = newValue;}

public void applyBrake(int decrement) {speed -= decrement;

}}

public void speedUp(int increment) {speed += increment;

}}}

Page 22: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

ConstructorsConstructors

class Bicycle {

public Bicycle(int startSpeed, int startGear) {gear = startGear;speed = startSpeed;

}}public Bicycle() {

gear = 1;speed = 0;

}

/** Omit the rest of the class definition*/

public static void main(String[] args) {Bicycle myBike = new Bicycle(0, 8);Bicycle otherBike = new Bicycle();

}}}

Page 23: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Constructors

MUST have same name as classMUST NOT have a return type

Constructors

MUST NOT have a return typeIf no constructor is supplied, the compiler creates a default constructor to initialize instance members.

modifiers classname (parameter list) throws exceptionlist {// method body

}

Page 24: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Taking out the garbage

The Java VM includes an automatic Garbage Collector!

Taking out the garbage

References are dropped when a variable goes out of scope, or is set to something else.

Garbage collector runs in background, cleaning up orphaned objects, freeing up memory.

Page 25: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Variable types

The type of variable is determined entirely by the location of its declaration plus the static keyword.

Variable types

Instance field – non-staticClass field – staticLocal variables & parameters – within method body / declaration

class TypesDemo {

int instanceVar;

static int classVar;

public static void main(String[] parameter) {int localVar;

}}

Page 26: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Look at this

Local variables and parameters can shadow class fields.

Look at this

public MyClass {int variable = 0;public int doMath(int variable){

return variable + this.variable; // instance variable}}

}

Thi b d t ll t t f th fi t li f th t tThis can be used to call constructors from the first line of another constructor.

public MyClass {public MyClass() {p y {

this(2);}public MyClass(int i) { ... }

}

Page 27: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

public class Bicycle {p y {

// the Bicycle class has two fieldspublic int gear;public int speed;

// the Bicycle class has one constructorpublic Bicycle(int startSpeed, int startGear) {

gear = startGear;speed = startSpeed;

members

}

// the Bicycle class has three methodspublic void setGear(int newValue) {

gear = newValue;gear = newValue;}

public void applyBrake(int decrement) {speed -= decrement;

}}

public void speedUp(int increment) {speed += increment;

}}}

Page 28: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Default Initialization (fields only)Default Initialization (fields only)

Data Type Default Value (for fields)

byte 0

short 0

int 0

long 0L

float 0 0ffloat 0.0f

double 0.0d

char '\u0000'

String (or any object) null

boolean false

Page 29: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Static Initializers

A field or static field may be initialized at it’s declaration:

public static final int NORTH 1;

Static Initializers

public static final int NORTH = 1;private int direction = NORTH;

A static initialization block can execute statements when the class is first loaded:A static initialization block can execute statements when the class is first loaded:

static {// whatever code is needed for initialization goes here

}}

Or, you could use a private static method (which could be reused later, if necessary):

public static varType myVar = initializeClassVariable();private static varType initializeClassVariable() {

//initialization code goes here}

Page 30: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Variable modifiers

// scope (applies only to fields)public int i; // class package subclass world

Variable modifiers

public int i; // class, package, subclass, worldprotected int i; // class, package, subclass

int i; // class, packageprivate int i; // class

// otherfinal int CONSTANT_VALUE; // fixed valuepublic static final int

UP = 1,UP 1,DOWN = 2; // can be used in a similar fashion to #DEFINE

Convention:

Constants use only uppercase letters with words separated by underscores.

Page 31: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Object-Oriented Programming

Java is Object-Oriented from the ground up.EVERYTHING is an Object Even primitives can be wrapped in Objects

Object Oriented Programming

EVERYTHING is an Object. Even primitives can be wrapped in Objects.Objects can have a lifetime greater than the object that created them.

An Object-Oriented language should support:

• Encapsulation - information hiding and modularity (abstraction)• Polymorphism behavior is dependent on the nature of the object receiving a• Polymorphism - behavior is dependent on the nature of the object receiving a

message • Inheritance - new classes are defined based on existing classes to obtain

code re-use and organization g• Dynamic binding - objects could come from anywhere, possibly across the

network. Send messages to objects without knowing their specific type at the time you write your code.

Page 32: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is an Object?

Bundling code into software objects provides a number of benefits, including:

What is an Object?

Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.

Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.

Code re-use: If an object already exists (perhaps written by another software developer), you can use th t bj t i Thi ll i li t t i l t/t t/d b l t k ifithat object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.

Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to y pp p g j p gfixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

Page 33: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Encapsulation

public class Bicycle {

Encapsulation

private int gear;private int speed;

public int getGear() { return gear; }p g () { g ; }

public void setGear(int newValue) {if (gear > 0) gear = newValue;

}

public int getSpeed() { return speed; }

public void applyBrake(int decrement) {speed -= decrement;

}

public void speedUp(int increment) {speed += increment;

}}}

Page 34: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

More Constructors

public class NoninstantiableClass {

More Constructors

private NoninstantiableClass() {// this can’t be instantiated by anybody else

}

public static NoninstantiableClass factoryMethod() {return new NoninstantiableClass();

}}

Page 35: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Nested Classes

class OuterClass {

Nested Classes

...public static class StaticNestedClass {

// Nested class}class InnerClass {{

// Inner (instance) class}public void foo() {

class LocalInnerClass {// L l i l// Local inner class

}Object o = new Object(){

// Anonymous inner class};

}}

Page 36: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is Inheritance?

Inheritance provides a powerful and natural mechanism for organizing and

What is Inheritance?

structuring your software.

A hierarchy of bicycles

Page 37: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is Inheritance?

Inheritance provides a powerful and natural mechanism for organizing and

What is Inheritance?

structuring your software.

class MountainBike extends Bicycle {

// new fields and methods defining a mountain bike would go here

}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique This makes code for your subclasses easy to readexclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

Page 38: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is Inheritance?

public class MountainBike extends Bicycle {

What is Inheritance?

p y {

// the MountainBike subclass adds one fieldpublic int seatHeight;

// the MountainBike subclass has one constructor// the MountainBike subclass has one constructorpublic MountainBike(int startHeight, int startSpeed, int startGear){

speed = startSpeedgear = startGear;seatHeight = startHeight;

}

// the MountainBike subclass adds one methodpublic void setHeight(int newValue) {public void setHeight(int newValue) {

seatHeight = newValue;}

}

Page 39: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Overriding methods and fields

public class Cat extends Animal {public void testInstanceMethod() {

Overriding methods and fields

public void testInstanceMethod() {System.out.println("The instance method in Cat.");

}public static void main(String[] args) {

Animal myAnimal = new Cat();myAnimal.testInstanceMethod();

}}class Animal {

public void testInstanceMethod() {public void testInstanceMethod() {System.out.println("The instance method in Animal.");

}}

The instance method in Cat.

Page 40: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Super

public class Subclass extends Superclass {public void printMethod() { //overrides printMethod in Superclass

Super

public void printMethod() { //overrides printMethod in Superclasssuper.printMethod();System.out.println("Printed in Subclass");

}public static void main(String[] args) {

Subclass s = new Subclass();s.printMethod();

}}class Superclass {class Superclass {

public void printMethod() {System.out.println("Printed in Superclass.");

}}

Printed in Superclass.Printed in SubclassPrinted in Subclass

Page 41: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Super constructors

public class MountainBike extends Bicycle {

Super constructors

p y {

// the MountainBike subclass adds one fieldpublic int seatHeight;

// the MountainBike subclass has one constructor// the MountainBike subclass has one constructorpublic MountainBike(int startHeight, int startSpeed, int startGear){

speed = startSpeedgear = startGear;seatHeight = startHeight;

}

// the MountainBike subclass adds one methodpublic void setHeight(int newValue) {public void setHeight(int newValue) {

seatHeight = newValue;}

}

Page 42: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Super constructors

public class MountainBike extends Bicycle {

Super constructors

p y {

// the MountainBike subclass adds one fieldpublic int seatHeight;

// the MountainBike subclass has one constructor// the MountainBike subclass has one constructorpublic MountainBike(int startHeight, int startSpeed, int startGear){

super(startSpeed, startGear);

seatHeight = startHeight;}

// the MountainBike subclass adds one methodpublic void setHeight(int newValue) {public void setHeight(int newValue) {

seatHeight = newValue;}

}

Page 43: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Object references and casting

// primitives

Object references and casting

int i = 0;int j = i;j = 1;System.out.println("i = " + i); // i = 1

MountainBike mountainBike = new MountainBike();Bicycle bike = mountainBike; // automatically castedObject o = bike; // all classes descend from Object

M t i Bik ()o = new MountainBike();if (o instanceof MountainBike) {

mountainBike = (MountainBike)o; // cast it back}

o = new Object();mountainBike = (MountainBike)o; // ClassCastException at runtime

Page 44: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Casting and promotion

int i;double d = 2 75;

Casting and promotion

double d = 2.75;

//compiler generates warning if cast is not present:i = (int)d; // i is 2

i = 2;d = i; // less exact numbers are automatically promoted

Integer intObject;intObject = i; // autoboxing automatically converts primitivesintObject i; // autoboxing automatically converts primitivesintObject = new Integer(i); // equivalent, but unneccessary

Object o = intObject; // automatic promotionint x = (Integer)o; // must be cast

Page 45: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Final

A final class is a class cannot be subclassed.

Final

A final method is a method that cannot be overridden.

public final class String {// ...

}

public class Object {public final Class getClass(){

// ...}}

}

Page 46: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Abstract

An abstract class is a class that is declared abstract—it may or may not include abstract th d Ab t t l t b i t ti t d b t th b b l d

Abstract

methods. Abstract classes cannot be instantiated, but they can be subclassed.

An abstract method is a method that is declared without an implementation

abstract class GraphicObject {int x, y;void moveTo(int newX, int newY) {( , ) {

//...}abstract void draw();

}

Page 47: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

What is an Interface?

An interface is a contract between a class and the outside world. When a class implements i t f it i t id th b h i bli h d b th t i t f

What is an Interface?

an interface, it promises to provide the behavior published by that interface.

interface Bicycle {// constant declarations, if anypublic static final MAX_GEAR = 10;

void changeGear(int newValue) //interfaces are completely abstractvoid changeGear(int newValue); //interfaces are completely abstractvoid speedUp(int increment);public abstract void applyBrakes(int decrement); // implied

}

class ACMEBicycle implements Bicycle {// remainder of this class implemented as before

}

Page 48: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Interface Types

Interface types work just like class types.

Interface Types

yp j yp

{public interface Relatable {/*** this (the object calling isLargerThan) and* other must be instances of the same class* returns 1, 0, -1 if this is greater, , g* than, equal to, or less than other*/

public int isLargerThan(Relatable other);}

public boolean isEqual(Relatable rel1, Relatable rel2) {if (rel1.isLargerThan(rel2) == 0) return true;else return false;

}}

Page 49: Tony Valderrama, SIPB IAP 2009Programming in Java Tony Valderrama, SIPB IAP 2009 Ti liTimeline Java 1.1 Microsoft develops own VM James Gosling creates Oak Java 2 (v1.3.1) Hotspot

Tony Valderrama, SIPB IAP 2009Programming in Java

Extending interfaces

public interface DoIt {

Extending interfaces

public interface DoIt {void doSomething(int i, double x);int doSomethingElse(String s);

}

public interface DoItPlus extends DoIt {boolean didItWork(int i, double x, String s);

}