Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using the new operator in Java Example public static void main() { int size = 1000; HashTable h; Foo myfoo = new Foo(); h = new HashTable(size);... January 24, 2003 Copyright 2003 by Bill Havens 1 of 22
Gotchas New continued Objects are not allocated automatically in Java (cf- C++) You must use the new operator explicitly to create each instance Example again: public static void main() { int size = 1000; HashTable h; Foo myfoo = new Foo(); System.out.println(myfoo) System.out.println(h) h = new HashTable(size); System.out.println(h)... // prints FooXXXXXXXX // prints null // prints HashTableXXXXXXXX January 24, 2003 Copyright 2003 by Bill Havens 2 of 22
Details All Object variables in Java are called Reference Variables More details in the next lecture Reference variables must be explicitly assigned instances of their class Arrays in Java Arrays are considered Objects in Java But with the familiar subscript syntax of C (example: x[i] = x[j]+1;) BUT you must create new instances of arrays explicitly Example: public static void main() { int size = 1000; int[] x = new int[size]; January 24, 2003 Copyright 2003 by Bill Havens 3 of 22
Making new instances of a class Constructors Classes represent ALL of their potential instances Need a method of constructing new instances from the class Special method with the same name as the class Can be heavily overloaded Default Constructor By default, Java provides a constructor with no arguments that does nothing Example: public foo() { Rule: if you need a different constructor then Java does not provide even the no arg constructor January 24, 2003 Copyright 2003 by Bill Havens 4 of 22
Example: class foo { private int n; protected double[] hist; private long width; // better! public foo( int nn ) { n = nn; hist = new double[nn]; What is the utility of a constructor? Constructors should be called Initializers Provide sometimes necessary initial states for each object instance Example above: variable n needs to have a starting value and the double[] needs to be created. January 24, 2003 Copyright 2003 by Bill Havens 5 of 22
Review Constructors Summarized Every class has at least one constructor Default constructor provided by Java has no arguments and does nothing Useful for constructing uninitialized instances of the class If your class instances need initial state or contain references to other objects then you need a custom constructor If you define a constructor, you must also define the null constructor Syntax: the form of the constructor public foo(<arg>,... ) where foo is the class name and the <arg>s define the constructor signature January 24, 2003 Copyright 2003 by Bill Havens 6 of 22
Introduction Inheritance Complex in other OOP languages but simplified in Java Inheritance is a fundamental concept in Object Programming. Complex objects (classes) can be expressed as refinements to more basic objects. Many classes can inherit the same basic behaviour from a common parent class. Supports code reuse in large systems. Supports well structured knowledge representation. Java supports single inheritance but with multiple interfaces More on Interface Classes later January 24, 2003 Copyright 2003 by Bill Havens 7 of 22
Basic Ideas: Classes can inherit members (both data and procedure) from another class (called its SuperClass) Every class has exactly one superclass (defaults to class Object) All public and protected members of the superclass are also members of the subclass. Inheritance is transitive Each instance of the subclass contains its own copies of the members from the superclass (but static members are NOT inherited) January 24, 2003 Copyright 2003 by Bill Havens 8 of 22
Example: Geometric Shapes Consider a graphics program for rendering geometric shapes. Every shape has a location (point) on the screen and a fill_pattern for colouring the object. There are many types of geometric objects (subclasses of shape). Each subclass has specific (more complex) behaviour than the parent class shape. BUT inherits basic behaviour from the parent class. Examples: circle and rectangle. How can we organize our knowledge hierarchy to use class hierarchy? January 24, 2003 Copyright 2003 by Bill Havens 9 of 22
Knowledge Hierarchy Subclass inheritance forms a hierarchy (called the class hierarchy) For single inheritance, the hierarchy is a tree. Example: Geometric Shape knowledge hierarchy Shape Subclass Circle Rectangle Subclass inherits ALL the members (variables and methods) of the parent class. May define additional members as necessary. January 24, 2003 Copyright 2003 by Bill Havens 10 of 22
abstract class Shape { protected point xy; protected int fill_pat; public Shape(); public Point getpoint(); public void setpoint(point);... abstract public float area(); abstract public void draw(); Example: Shape Class // location of shape // rendering fill pattern // constructor // return location of Shape // set location // area of any shape // render any shape Use of keyword protected means that members are NOT part of public interface but accessible to any subclass. Keyword abstract means that only the class protocol is described and NOT (all of) the method implementation January 24, 2003 Copyright 2003 by Bill Havens 11 of 22
class Circle extends Shape { protected double radius; Subclass Circle public Circle(float r) { super(); radius = r; // make a circle with radius r // make the superclass instance first public float getradius() { return radius; public void setradius(double r) { radius = r; public void draw() { draw something // draw defined in this class. public float area() { return Math.pi*radius*radius;... Creating a new Circle creates a new Shape as part of the derived class. January 24, 2003 Copyright 2003 by Bill Havens 12 of 22
Another Inheritance Example Example: redefined class Sphere from textbook NOTE: extends class Circle Note that a default constructor must be coded Any constructors in the superclass MUST be called first public class Sphere extends Circle { // default constructor public Sphere() { super(1.0); // unit sphere // custom constructor public Sphere(double initialradius) { super(initialradius); January 24, 2003 Copyright 2003 by Bill Havens 13 of 22
more Methods equals() predicate overrides method in class Object Illustrates instance-of predicate and type casting Type Casting Operator (<type>)<exp> changes type of <exp> to <type> public boolean equals(object rhs) { return ((rhs instanceof Sphere) && (radius == ((Sphere)rhs).radius)); Overrides setradius() in class Circle public void setradius(double newradius) { if (newradius >= 0.0) this.radius = radius; else throw new IllegalArgumentException( negative radius ); Accessor illustrates throwing exceptions and use of this variable NOTE: runtime exceptions need not be caught (more later) January 24, 2003 Copyright 2003 by Bill Havens 14 of 22
more Methods public double diameter() { return 2.0 * radius; Note inefficiency of diameter() call public double circumference() { return Math.PI * diameter(); public double area() { return 4.0 * Math.PI * radius * radius; Note inefficiency of Math.pow() call public double volume() { return (4.0*Math.PI * Math.pow(radius, 3.0)) / 3.0; January 24, 2003 Copyright 2003 by Bill Havens 15 of 22
Redefining the tostring() method from class Object // NOTE: replaces displaystatistics() from textbook public String tostring () { return "\nradius = " + radius() + "\ndiameter = " + diameter() + "\ncircumference = " + circumference() + "\narea = " + area() + "\nvolume = " + volume(); //end class Sphere NOTE: inefficient method calls Next we will consider extending this class again January 24, 2003 Copyright 2003 by Bill Havens 16 of 22
Class Ball More practice in inheritance in Java We need to model a ball for some computer game perhaps Reuse existing code from Sphere plus new operations Some methods will be overriden to provide more specialized behaviour I am really a sphere A Ball is a sphere plus more semantics January 24, 2003 Copyright 2003 by Bill Havens 17 of 22
Class Ball public class Ball extends Sphere { private String thename; // the ball's name // create a default ball with unit radius an unknown name public Ball() { setname("unknown"); Default constructor for Sphere will automatically be called // Creates a ball with specified radius and name public Ball(double initialradius, String initialname) { super(initialradius); setname(initialname); Note that we had to call super constructor explicitly More operations specific to Ball... January 24, 2003 Copyright 2003 by Bill Havens 18 of 22
more Methods for class Ball public boolean equals(object rhs) { return ((rhs instanceof Ball) && (radius == ((Ball)rhs).radius) && (thename.equals(((ball)rhs).thename); Overrides equals() defined in Sphere Simplified name comparison to use equals() in class String more Accessors made final (why?) public final String name() { return thename; public final void setname(string newname) { thename = newname; January 24, 2003 Copyright 2003 by Bill Havens 19 of 22
more Accessors Reset the ball to new radius and name Is this a good idea? Consider the equals() predicate public void resetball(double newradius, String newname) { setradius(newradius); setname(newname); What are the method calls for? Override the tostring() method in Sphere Note: not using displaystatistics() from textbook public String tostring() { return thename + super.tostring(); Reuse the tostring() method from Sphere via the super keyword // end Ball January 24, 2003 Copyright 2003 by Bill Havens 20 of 22
Inheritance in Class Ball Note: displaystatics() replaced via tostring() Ball inherits all data and methods from Sphere BUT Adds variable thename and Overrides method definitions for equals() and tostring() January 24, 2003 Copyright 2003 by Bill Havens 21 of 22
Runtime Method Dispatching public static void main() { Sphere s = new Sphere(); Ball b = new Ball(12.0, soccer ball ); System.out.println( my sphere is +s); System.out.println( my ball is +b); Sphere x = b; System.out.println( my other sphere is really a ball = +x); Which tostring() methods are called? Rule: Java determines the type of the object instance at runtime and invokes the method defined in the actual type of the class. Compare to C++ which uses the type of the variable at compile time (unless the method is declared virtual) January 24, 2003 Copyright 2003 by Bill Havens 22 of 22