object-oriented programming with java classes and inheritance lecture 2

24
Object-Oriented Object-Oriented Programming with Programming with Java Java Classes and Inheritance Classes and Inheritance Lecture 2 Lecture 2

Upload: laura-lindsey

Post on 14-Dec-2015

221 views

Category:

Documents


3 download

TRANSCRIPT

Object-Oriented Object-Oriented Programming with JavaProgramming with Java

Classes and InheritanceClasses and Inheritance

Lecture 2Lecture 2

Object-Orientation & JavaObject-Orientation & Java

ContentsContents Object-Oriented Programming in JavaObject-Oriented Programming in Java Fields and methodsFields and methods Implementing InheritanceImplementing Inheritance Method overloadingMethod overloading Abstract classesAbstract classes

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() {…}

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

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

Class MethodsClass Methods

public static double public static double radiansToDegrees(double rads) {radiansToDegrees(double 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);

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?

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();

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

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);

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 a simple example of This is a simple example of method method overloadingoverloading

Method OverloadingMethod Overloading

Definition of multiple methods with the Definition of multiple methods with the same name.same name.

This is perfectly legal in Java, provided This is perfectly legal in Java, provided each version of the method has a different each version of the method has a different parameter list (so there is no ambiguity)parameter list (so there is no ambiguity)

E.g.E.g. Circle( )Circle( ) Circle(double r)Circle(double r)

This and thatThis and that

Consider the following code fragment:Consider the following code fragment:Circle c = new Circle(1.0);Circle c = new Circle(1.0);double a = c.area();double a = c.area(); What are those empty parentheses doing there?What are those empty parentheses doing there? How does a function with no parameters know How does a function with no parameters know

what data to operate on?what data to operate on? There is an implicit argument named There is an implicit argument named thisthis::

Holds a reference to the object Holds a reference to the object cc We also use “We also use “thisthis” in order to make it clear an ” in order to make it clear an

object is accessing its own fields object is accessing its own fields

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

Implementing InheritanceImplementing Inheritance

Circle

radius

circumferencearea

PlaneCircle

cxcy

isInside

““PlaneCircle” as a subclassPlaneCircle” as a subclasspublic class PlaneCircle extends Circle {

}

public double cx, cy;

public PlaneCircle(double r, double x, double y) { super(r); this.cx = x; this.cy = y;}

// automatically inherit fields and methods of Circle

PlaneCircle

cxcy

isInside

public boolean isInside(double x, double y) { …}

Subclass ConstructorsSubclass Constructors

In this case, the word “super”:In this case, the word “super”: Invokes the constructor method of the superclassInvokes the constructor method of the superclass Must only be used in this way within a constructor Must only be used in this way within a constructor

methodmethod Must apear within the first statement of the Must apear within the first statement of the

constructor methodconstructor method

public PlaneCircle(double r, double x, double y) { super(r); // invoke constructor of superclass this.cx = x; // initialise instance field cx this.cy = y; // initialise instance field cy}

Making more circlesMaking more circles

PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0);PlaneCircle pc = new PlaneCircle(1.0, 0.0, 0.0);// Create a unit circle at the origin// Create a unit circle at the origin

double a = pc.area( );double a = pc.area( );// Calculate it’s area by invoking an inherited method// Calculate it’s area by invoking an inherited method

boolean test = pc.isInside(1.5, 1.5); boolean test = pc.isInside(1.5, 1.5); // Test if the point (1.5, 1.5) is inside the PlaneCircle pc // Test if the point (1.5, 1.5) is inside the PlaneCircle pc

or notor not

What other methods might we want in What other methods might we want in PlaneCircle?PlaneCircle?

Overriding methodsOverriding methodsAccount

numberbalance

creditdebit

SavingsAccount

creditdebit

Method OverridingMethod Overriding

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 }}

public class SavingsAccount extends

Account {

// instance fields inherited

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

Overloading vs. OverridingOverloading vs. Overriding

Overloading: Multiple methods with the Overloading: Multiple methods with the same namesame name In the same class, butIn the same class, but Different parameter listsDifferent parameter lists

Overriding: Multiple methods methods with Overriding: Multiple methods methods with the same namethe same name With exactly the same signatures, butWith exactly the same signatures, but In different classes in an inheritance hierarchyIn different classes in an inheritance hierarchy

Abstract ClassesAbstract Classes

EllipticalShape

circumferencearea

Circle

radius

Ellipse

semiMinorAxissemiMajorAxis

Abstract ClassesAbstract Classes

An An abstractabstract class cannot be instantiated class cannot be instantiated A subclass of an A subclass of an abstractabstract class can class can

only be instantiated if:only be instantiated if: It overrides each of the It overrides each of the abstractabstract methods of methods of

its superclass, andits superclass, and Provides a concrete implementation of them Provides a concrete implementation of them

It’s then known as a It’s then known as a concrete classconcrete class

Java DefinitionJava Definition

public abstract class Elliptical Shape {

public abstract double area( ) ; public abstract double circumference( ) ;

// Note semicolons instead of body of methods

}