Download presentation
Presentation is loading. Please wait.
Published byDamian Johnston Modified over 6 years ago
1
Tirgul 4 Reference variables Method overloading The keyword “this”
Javadoc Interface vs. implementation Bottom-up design
2
Primitive types Primitive variables correspond to memory locations which store their current value i 5 int i = 5; int j = i; i = 6; memory addresses i j 5 i j 6 5
3
Reference variables Reference variables store the memory address of an object Date d = new Date(1,2,99); Date d = new Date(1,2,99); . . . 300 1 2 99 d _day _month _year
4
Different objects with the same attributes
Date d1 = new Date(1,2,99); Date d2 = new Date(1,2,99); Date d1 = new Date(1,2,99); Date d2 = new Date(1,2,99); Date d1 = new Date(1,2,99); Date d2 = new Date(1,2,99); d d2 300 . . . 1 2 99 _day _month _year 400 d1.setYear(88); 1 2 99 _day _month _year . . . . . . 300 400 1 2 88 d d2 _day _month _year
5
Different references to the same object
Date d1 = new Date(1,2,99); Date d2 = d1; d d2 300 . . . 1 2 99 _day _month _year d1.setYear(88); d d2 300 . . . 1 2 88 _day _month _year
6
Comparing references Date d1 = new Date(1,2,99);
if (d1 == d2) System.out.print(“Same date”); else System.out.print(“Different”);
7
Comparing objects Add a method to class Date:
public boolean equals(Date other) { if (other == null) return false; return (_day == other._day) && (_month == other._month) && (_year == other._year); }
8
Comparing objects Date d1 = new Date(1,2,99);
if (d1.equals(d2)) System.out.print(“Same date”); else System.out.print(“Different”);
9
null references The keyword null signifies an invalid memory address
Any reference variable may be set to null Date d = null; Attempting to access the members of a null reference will cause a runtime exception
10
Method overloading Different methods can have the same name, as long as they differ in their number/type of arguments System.out.print(int) System.out.print(double) int parseInt(String s) int parseInt(String s, int base)
11
The keyword “this” In non-static methods, the keyword this represents a local variable referring to the object on which the method was called public Date someMethod() { this._day++; // same as _day++ someOtherMethod(this); return this; }
12
Using “this” in constructors
The first statement in a constructor may call another constructor using “this” public Date(int day, int month, int year) { _day = day; _month = month; _year = year; } public Date() { // default date: 1/1/80 this(1,1,80); // we could do more things here
13
The ternary operator ?: Shorthand for an if-then-else statement
<condition> ? <value if true> : <value if false> Example: public int absoluteValue(int a) { return a<0 ? –a : a; } Equivalent to: if (a<0) return –a; else return a;
14
Javadoc You must write documentation comments (starting with /**) for ALL classes, data members, and methods (public and private) For methods, tags Create HTML documentation from your sources: javadoc –private –d doc *.java This command should execute with no warnings/errors!
15
Javadoc example /** This class represents a calendar date @author John Doe */ public class Date { /** The year of this date */ private int _year; /** Checks whether another Date is equal to this one @param other The object with which to compare this Date @return true iff this object represents the same date as other */ public boolean equals(Date other) {…}
16
Bottom-up design Identify the classes (sub-tasks) we will need in our program Start with the details Work our way up until the main method can be implemented Keep the solution general (and therefore reusable)
17
Example: quadratic equations
We would like to find all the (possibly complex) solutions z to the equation: az2 + bz + c = 0 The user will provide the coefficients a,b,c Start at the bottom: a class to represent a complex number, then a class to represent the solution(s) to an equation…
18
Complex numbers A complex number z may be described in (at least) two ways: Cartesian (x,y) Polar (φ,r)
19
Interface vs. implementation
The user of the Complex class does not (and should not) care how the numbers are represented internally Implementation details are private All the user needs is a well-defined set of methods providing all the necessary functionality (API) Only the public interface is exposed
20
Class design QuadDriver QuadSolver QuadSolution Complex
21
The Complex class /** This class represents a complex number */
public class Complex { private double _real; private double _imaginary; /* Constants allowing the user to specify Cartesian/polar representation */ public static final int REP_CARTESIAN = 0; public static final int REP_POLAR = 1; We chose to use Cartesian representation internally, but the user of the class does/should not know it
22
Complex constructor /** Construct a new Complex object given either its Cartesian or polar representation */ public Complex(int representation, double realOrRadians, double imaginaryOrLength) { if (representation == REP_CARTESIAN) { _real = realOrRadians; _imaginary = imaginaryOrLength; } else { // representation == REP_POLAR _real = imaginaryOrLength * Math.cos(realOrRadians); _imaginary = imaginaryOrLength * Math.sin(realOrRadians);
23
More Complex constructors
/** If no representation is given, assume Cartesian */ public Complex(double real, double imaginary) { this(REP_CARTESIAN, real, imaginary); } /** Default ctor: the complex number 0 */ public Complex() { this(REP_CARTESIAN, 0.0, 0.0); /** Copy ctor: make a copy of other */ public Complex(Complex other) { this(REP_CARTESIAN, other._real, other._imaginary);
24
Complex getters /** Return the real part of this complex number */
public double getReal() { return _real; } /** Return the imaginary part of this complex number */ public double getImaginary() { return _imaginary; /** Return the length of this complex number */ public double getLength() { return Math.sqrt(_real * _real + _imaginary * _imaginary);
25
getRadians /** Return the angle of this complex number in radians relative to the positive side of the X axis. The return value is in the range (-pi,pi]. For the zero complex number, return 0. */ public double getRadians() { if (_real==0 && _imaginary==0) return 0.0; // arbitrary if (_real==0) // and _imaginary!=0 return _imaginary>0 ? Math.PI/2 : -Math.PI/2; if (_imaginary==0) // and _real!=0 return _real>0 ? 0 : Math.PI; return Math.acos(_real / getLength()) * // angle (_imaginary / Math.abs(_imaginary)); // sign }
26
getDegrees /** Return the angle of this complex number in degrees relative to the positive side of the X axis. The return value is in the range (-180,180]. */ public double getDegrees() { return getRadians() * (180 / Math.PI); }
27
Complex toString /** Return the polar String representation of this complex number using radians */ public String toStringPolarRadians() { return “<” + getRadians() + ’,’ + getLength() + ’>’; } /** Return the polar String representation of this complex number using degrees */ public String toStringPolarDegrees() { return “<” + getDegrees() + ’,’ + getLength() + ’>’;
28
More Complex toString /** Return the Cartesian String representation of this complex number */ public String toStringCartesian() { return “” + _real + ’+’ + _imaginary + ”*i”; } /** Return the default String representation of this object (used when printing objects via System.out.print). */ public String toString() { return toStringCartesian();
29
Complex add /** Adds the given complex number to this one. Assumes other is not null. Returns a reference to this number, allowing chaining, e.g. c.add(c1).add(c2) */ public Complex add(Complex other) { _real += other._real; _imaginary += other._imaginary; return this; } /** Return a new complex number which is the sum of the given number and this one */ public Complex addToCopy(Complex other) { Complex result = new Complex(this); return result.add(other);
30
Complex multiply /** Multiply this complex number by the given one. Return a reference to this number. */ public Complex multiply(Complex other) { double real = _real * other._real – _imaginary * other._imaginary; double imaginary = _real * other._imaginary + _imaginary * other._real; _real = real; _imaginary = imaginary; return this; }
31
Complex multiplyWithCopy
/** Return a new complex number which is the product of the given number and this one */ public Complex multiplyWithCopy(Complex other){ Complex result = new Complex(this); return result.multiply(other); }
32
Class design QuadDriver QuadSolver QuadSolution Complex
33
The QuadSolution class
/** This class represents the complex solution(s) to a quadratic equation. */ public class QuadSolution { private Complex _sol1, _sol2; private int _type; public static final int TYPE_NONE = 0; public static final int TYPE_LINEAR = 1; public static final int TYPE_QUAD = 2; public static final int TYPE_INFINITY = 3;
34
QuadSolution constructor
/** Construct a QuadSolution with the given solutions (either or both may be null) */ public QuadSolution(Complex sol1, Complex sol2) { if (sol1==null && sol2==null) { // no solutions _sol1 = _sol2 = null; _type = TYPE_NONE; } else if (sol1!=null && sol2!=null) { // 2 solutions _sol1 = new Complex(sol1); // save copies of the given objects! _sol2 = new Complex(sol2); _type = TYPE_QUAD; else { // 1 solution _sol1 = (sol1 != null) ? new Complex(sol1) : new Complex(sol2); _sol2 = null; _type = TYPE_LINEAR;
35
Default constructor /** Construct a QuadSolution indicating that all numbers solve the equation */ public QuadSolution() { _type = TYPE_INFINITY; _sol1 = _sol2 = null; }
36
QuadSolution getters /** Return the type of this solution (one of the TYPE finals) */ public int getType() { return _type; } /** Return one of the solutions as specified by id (0 or 1). Returns null if the requested solution doesn’t exist. */ public Complex getSolution(int id) { switch (id) { case 0: // return a copy of _sol1! return (_sol1!=null) ? new Complex(_sol1) : null; case 1: // return a copy of _sol2! return (_sol2!=null) ? new Complex(_sol2) : null; default: // invalid id return null;
37
QuadSolution toString()
/** Return a String representation of this solution */ public String toString() { switch (_type) { case TYPE_NONE: return “No solutions”; case TYPE_LINEAR: return _sol1.toString(); case TYPE_QUAD: return _sol1.toString + ‘,’ + _sol2.toString(); case TYPE_INFINITY: return “All numbers”; } return “”; // avoid compilation error
38
Class design QuadDriver QuadSolver QuadSolution Complex
39
The QuadSolver class /** This class knows how to solve a quadratic equation */ public class QuadSolver { /** Returns the solution to the equation az2 + bz + c = 0 */ public QuadSolution solve(double a, double b, double c){ if (a==0 && b==0 && c==0) //all numbers are solutions return new QuadSolution(); if (a==0 && b==0 && c!=0) // no solutions return new QuadSolution(null,null); if (a==0) // b!=0 so there is one solution return new QuadSolution(new Complex(-c/b,0),null);
40
QuadSolver continued // now we know the equation has degree 2
double discriminant = b*b – 4*a*c; double root = Math.sqrt(Math.abs(discriminant)); Complex sol1, sol2 = null; if (discriminant==0) // one real solution sol1 = new Complex(-b/(2*a),0); else if (discriminant<0) { // two complex solutions sol1 = new Complex(-b/(2*a), root/(2*a)); sol2 = new Complex(-b/(2*a),-root/(2*a)); } else { // two real solutions sol1 = new Complex((-b+root)/(2*a),0); sol2 = new Complex((-b-root)/(2*a),0)); return new QuadSolution(sol1,sol2);
41
Class design QuadDriver QuadSolver QuadSolution Complex
42
The QuadDriver class /** A program for solving a complex quadratic equation read from the user */ public class QuadDriver { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double a = scanner.nextDouble(); double b = scanner.nextDouble(); double c = scanner.nextDouble(); QuadSolver solver = new QuadSolver(); QuadSolution solution = solver.solve(a,b,c); System.out.print(solution); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.