java lecture 2

41
Java Lecture 2 John Black CS 425 Fall 2000

Upload: toya

Post on 21-Mar-2016

29 views

Category:

Documents


0 download

DESCRIPTION

Java Lecture 2. John Black CS 425 Fall 2000. Classes and Objects. We’ve already seen a number of examples public class Circle { public double x, y; // coordinates of center public double r; // length of radius public double perimeter(); { return 2*Math.PI*r; } - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Java Lecture 2

Java Lecture 2

John BlackCS 425

Fall 2000

Page 2: Java Lecture 2

Classes and Objects

• We’ve already seen a number of examplespublic class Circle {

public double x, y; // coordinates of centerpublic double r; // length of radiuspublic double perimeter(); { return 2*Math.PI*r; }public double area(); {return Math.PI*r*r; }

}Circle c = new Circle(); // default constructordouble a;c.x = 2.0; c.y = 2.0; c.r = 1.0;a = c.area();

Page 3: Java Lecture 2

The “this” Pointer

• How does a method know what parameters to operate on? Defaults to “this” object.

• “this” is a reference to the current instancepublic double area() { return Math.PI * this.r * this.r }

• You don’t need “this” above; it’s implied, but there are cases where it is needed (eg, if you had a local with the same name as a field of the class)

Page 4: Java Lecture 2

Constructors

• Let’s make an explicit constructor for Circlepublic Circle(double x, double y, double r){

this.x = x; this.y = y; this.r = r;}

• Now we can create a circle in one step:Circle c = new Circle(2.0, 2.0, 1.0);

• Note: no return value (“this” is implicitly returned)

Page 5: Java Lecture 2

More on Constructors

• Multiple constructors are allowed:

public Circle(double r) { x=0.0; y=0.0; this.r=r; }public Circle(Circle c) { x=c.x; y=c.y; r=c.r; }public Circle() { x=0.0; y=0.0; r=1.0; }

• Unlike C++, java does not have default parameters

Page 6: Java Lecture 2

“this” Again

• Another use for “this” is with constructors:public Circle(double x, double y, double r) {

this.x = x; this.y = y; this.r =r ;}public Circle(double r) { this(0.0, 0.0, r); }public Circle(Circle c) { this(c.x, c.y, c.r); }public Circle() { this(0.0, 0.0, 1.0); }

• “this” must appear as the first statement in the constructor (if at all); explanation later

Page 7: Java Lecture 2

Class Variables

• Use the classifier “static” to create a class variable (as opposed to an instance variable)– Only one copy of this variable– Need not instantiate the class to access

(Math.PI is an example)– static != final (ie, class variables can be altered)

Page 8: Java Lecture 2

Class Variables (example)

public class Circle {static int num_circles = 0; // class variablepublic double x, y, r;public Circle(double x, double y, double r) {

this.x = x; this.y = y; this.r = r;num_circles++;

}public Circle(double r) { this(0.0, 0.0, r); }etc…

}// num_circles tracks the number of circles created

Page 9: Java Lecture 2

Class Variables (cont.)

• To access class variables use class name dot variable name

System.out.println(Circle.num_circles);• No globals in java, but a class variable is

just like one!• Class variables always have a unique name

(why?)

Page 10: Java Lecture 2

Class Methods

• Class methods declared with “static” keyword

• Operate only on parameters (not on instance variables because there aren’t any!)

• Ex: java.lang.Math class has only class variables and methods (eg, Math.sqrt())

• Which is better: Math.sqrt(d); or d.sqrt(); ?

Page 11: Java Lecture 2

Class Methods (cont.)

• There is no “this” (why not?)• A mystery explained:

System.out.println(“hi”);• java.lang.System is a class• This class has a class variable

static PrintStream out;• println() is an instance method for “out”

Page 12: Java Lecture 2

Static Initializers

• How do we initialize class variables?– int x = 1; // fine for simple cases

• Initialization occurs when class is loadedstatic {

// initialization code goes here}

• Notice: no name, no parameters, no return value• Any number of static initializers allowed within

class declaration

Page 13: Java Lecture 2

Object Destruction

• Java automatically garbage collects when an object no longer has any references

• A low priority thread performs this work in the background (while i/o is occurring, eg)

• Helps reduce bugs in code!• Can force garbage collection:

StringBuffer[] b = new StringBuffer[100];….b = null;

Page 14: Java Lecture 2

The finalizer() Method

• The finalizer() is called is called just before java is going to garbage collect an object– The finalizer() should clean up system resources

associated to the object– Must be an instance method, no args, no return

protected void finalize() throws IOException {if (fd != null)

close();}

Page 15: Java Lecture 2

Subclasses and Inheritance

• To subclass a class, use “extends”:public class GraphicCircle extends Circle {

// omitting constructor for nowColor outline, fill;public void draw(DrawWindow dw) {

dw.drawCircle(x, y, r, outline, fill);}

}• The public variables x, y, and r, and public methods area()

and circumference() are inherited from the superclass Circle

Page 16: Java Lecture 2

Subclasses and Inheritance (cont.)

• “private” variables and methods not inherited (more on this later)

• We can treat a GraphicCircle object just like a Circle object:GraphicCircle gc = new GraphicCircle();double area = gc.area(); // calls Circle’s area()

• Is this legal: GraphicCircle gc = new GraphicCircle();Circle c = gc;

Page 17: Java Lecture 2

Subclasses and Inheritance (yes, there’s more)

• Don’t confuse package hierarchies with subclass hierarchies– java.io.InputStream is a subclass of java.lang.Object but we’d

never write Object.InputStream

• Am I a subclass?– Say we have an array: Circle[] c = new Circle[10];– Some are Circle objects and some may be

GraphicCircle objects; I want to write GraphicCircle gc = (GraphicCircle)c[4];but I’m worried I might get an error! What should I do?

Page 18: Java Lecture 2

Final Classes

• “final” essentially means “constant”• Classes declared “final” cannot be

subclassed • java.lang.System is an example• Advantages:

– Preserve control on class hierarchy– Allows some optimizations (more later)

Page 19: Java Lecture 2

Superclasses and “Object”

• Every class you define has a superclass• If you do not use “extends” when you create a

class, it becomes a subclass of the Object class• “Object” is the root of the class hierarchy

– “Object” has no superclass– The methods of “Object” can be called by any java

object (why?)• java.lang class hierarchy is on p. 329 of Java in a

Nutshell, 3rd ed.

Page 20: Java Lecture 2

Constructors in a Subclass

• Let’s write a GraphicCircle constructor:public GraphicCircle(double x, double y, double r,

Color outline, Color fill){

this.x = x; this.y = y; this.r = r;this.outline = outline; this.fill = fill;

}• Does this work? What if the Circle

constructor had private fields?

Page 21: Java Lecture 2

A Better Way to Create Subclass Constructors

• Instead, rewrite the GraphicCircle:public GraphicCircle(double x, double y, double r,

Color outline, Color fill){

super(x, y, r);this. outline = outline; this.fill = fill;

}• Same restrictions as using “this” as a constructor

call:– “super” must be first statement in the constructor

Page 22: Java Lecture 2

Constructors and Superclasses

• How does the superclass get created if we don’t call super()?– super() is automatically called

• exception: if there is a this() constructor call

– (What happens if the superclass doesn’t have a constructor with no arguments?)

• What happens when we call our GraphicCircle constructor?

• Explicitly calls Circle constructor• Circle’s constructor implicitly calls Object constructor

Page 23: Java Lecture 2

Default Constructors

• What if a class has no constructor at all?– Java automatically provides a default like this:

• public GraphicClass() { super(); }

– If superclass (Circle) did not have a no-arg constructor, we’d get an error

– Good practice to at least comment that you are relying on a default constructor

– Default constructors are “public”; declare it “protected” if you want to restrict to same package and subclasses

• What happens if we declare a constructor “private”?

Page 24: Java Lecture 2

Shadowed Variables

• What if a variable “v” in my class uses the same name as a variable “v” in my superclass?– The superclass variable is said to be “shadowed”– Can access the superclass variable “ v” with “super.v”– Can also cast to the superclass’s class (or any

superclass in the class hierarchy): eg, (Circle)gc.r• Probably best to just avoid shadowing

Page 25: Java Lecture 2

Method Overriding

• If a subclass declares a method with the same name as a superclass method, this is called “method overriding”– Method Overriding is not Variable Shadowing– We actually will often want to override

methods (eg, a subclass computes area() differently than the Circle area() method)

– Cannot use casting to access overridden methods

Page 26: Java Lecture 2

Example of Method Overriding

• Consider this example:public class A {

public f( ) {….}}public class B extends A{

public f( ) {….}}B b = new B( );A a = b;a.f( );

• Which method is called?• This is called “Dynamic Method Lookup”• In C++ only “virtual” functions work like this; in Java all

functions are virtual by default

Page 27: Java Lecture 2

Final Methods

• Methods declared “final” cannot be overridden

• Other methods which cannot be overridden include static methods, private methods (later) and the methods of a final class

• If we cannot override, the compiler can make static references and possibly even inline the functions

Page 28: Java Lecture 2

Invoking an Overridden Method

• We can use super.f() to invoke an overridden method

• super.super.f() is not valid; there is no way to invoke an overridden overridden method

Page 29: Java Lecture 2

Visibility Modifiers

• The Java visibility modifiers are “public,” “package,” “protected,” and “private”– public: visible everywhere– package: visible only within current package– protected: visible within package and to all subclasses– private: visible only within current class

• “package” is the default (package visibility means all classes are friendly, in C++ terms)

Page 30: Java Lecture 2

Which One Should I Use??

• Use “public” for APIs• Use “protected” for hiding data, but allowing

subclasses in different packages to access this class member

• Use “private” for anything internal or even for API variable which have public accessor methods (sometimes “protected” is better for this though)

Page 31: Java Lecture 2

Abstract Classes

• An abstract class is a class which does not implement some of its methods– Imagine a new class “Shape”

• Subclasses of “Shape” include “Circle,” “Square,” “Triangle,” etc.

• Each of these has a method called perimeter() but “Shape” does not implement this method (why not?)

• Why should “Shape” even bother to declare this method?

• In C++ we would use a “pure virtual function” within a class to make it abstract

Page 32: Java Lecture 2

Abstract Classes (cont.)

• Rules for abstract methods:– If a class has an abstract method, the class must

be declared abstract– A class may be declared abstract even without

any abstract methods (prevents instantiation)– A subclass of an abstract class can be instantiated

provided it implements all of the superclass’s abstract methods (otherwise the subclass is also abstract)

Page 33: Java Lecture 2

Time for an (abstract) Example

public abstract class Shape {public abstract double area(); // note: no method body, no bracespublic abstract double perimeter();

}class Circle extends Shape {

protected double r;public Circle(double r) { this.r = r; }public double area() { return Math.PI * r * r; }public double perimeter { return Math.PI * 2 * r; }public double getRadius() { return r; }

}class Rectangle extends Shape {

protected double w, h; public Rectangle(double w, double h) { this.w = w; this.h = h; } public double area() { return w*h; } public double perimeter() { return 2 * (w+h); }

}

Page 34: Java Lecture 2

Using our Shape Class

Shape[ ] shapes = new Shape[3]; // huh? I thought this was illegal?

shapes[0] = new Circle(2.0);shapes[1] = new Rectangle(1.0, 3.0);shapes[2] = new Rectangle(4.0, 2.0);double total_area = 0;for (int i=0; i < shapes.length; i++)

total_area += shapes[ i ].area();• Things to notice:

– No casting is necessary to go up the class hierarchy– The appropriate method is automatically called– Can I write Circle c = shapes[0]; ? – How about Circle c = (Circle)shapes[1]; ? // java.lang.ClassCastException– What would have happened if we had added shapes[3] = new Shape();

Page 35: Java Lecture 2

Interfaces

• Java does not have multiple inheritance– What if we want multiple superclasses?– In java we can inherit actual methods from at

most one superclass, but we can inherit abstract methods from multiple other classes as well

– Many consider this mechanism more elegant than multiple inheritance (which is hard to use in a meaningful way anyway)

Page 36: Java Lecture 2

An Example Interface

• Say we want classes “DrawableCircle” and “DrawableRectangle”– These should subclass Circle and Rectangle so

we can inherit the area() and perimeter() methods

– Solution: declare a new interface “Drawable” and have DrawableCircle and DrawableRectangle implement it

Page 37: Java Lecture 2

An Example Interface (cont.)

public interface Drawable {public void setColor(color c);public void setPosition(double x, double y);public void draw(DrawWindow dw);

}• Things to note:

– Keyword “class” not used– All methods are abstract (can include this keyword if you

like)– Like abstract classes, interfaces cannot be instantiated

Page 38: Java Lecture 2

How to “implement” an Interface

public class DrawableRectangle extends Rectangle implements Drawable {private Color c;private double x, y;public DrawableRectangle (double w, double h) { super(w, h); }public void setColor(Color c) {this.c = c; }public void setPosition(double x, double y) {this.x = x; this.y = y; }public void draw(DrawWindow dw) { dw.drawRect(x, y, w, h, c); }

}• Things to Notice:

– “implements” names all interfaces implemented by this class– “implements” appears after the “extends” clause– Any class which implements an interface must provide methods for each

method listed in the interface’s definition (unless the class is abstract)

Page 39: Java Lecture 2

Using the Interface

Shape[] shapes = new Shape[3];Drawable[] drawables = new Drawable[3];DrawableCircle dc = new DrawableCircle(1.1);DrawableSquare ds = new DrawableSquare(2.5);DrawableRectangle dr = new DrawableRectangle(2.3, 4.5);

shapes[0] = dc; drawables[0] = dc;shapes[1] = ds; drawables[1] = ds; shapes[2] = dr; drawables[2] = dr;

double total_area = 0;for (int i = 0; i < shapes.length; i++) {

total_area += shapes[i].area();drawables[i].setPosition(i * 10.0, i * 10.0);drawables[i].draw(draw_window); // assume draw_window was defined

}

Page 40: Java Lecture 2

Further Notes on Interfaces

• Variables in interfaces must be “static final”– Unlike constants in classes, we do not need to prefix the constant

with the interface name– Provides an easy way for various classes to share a common set of

constants

• Interfaces may have sub-interfaces by being “extend”ed (we won’t discuss this)

• Marker Interfaces are empty interfaces used to mark a class (eg, java.lang.Cloneable)– Use “instanceof” to see if a class implements a marker interface:

if (item instanceof Cloneable) { Item b = (Item)item.clone();}

Page 41: Java Lecture 2

Further Differences between C++ and Java

• No templates in Java – Library functions operate on Objects in Java

• Pro: More object-oriented and cleaner• Con: Have to cast everything constantly

• Operator Overloading not supported in Java