Tirgul 4 Reference variables Method overloading The keyword “this”

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
JAVA Classes. Objectives Be able to define new classes Be able to define appropriate instance variables Be able to define the usual methods of a class.
1 CS2200 Software Development Lecture: Testing and Design A. O’Riordan, 2008 K. Brown,
1 Tirgul no. 3 Topics covered: H Iteration. H Defining and using classes.
1 Tirgul no. 4 Topics covered: H Defining classes H Documentation using javadoc H The computer memory during program execution.
Java Types float, double long, int, short byte char boolean Objects Objects are created by : Declaring a reference and calling a constructor. Basic types.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
The Java Programming Language
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Utilities (Part 2) Implementing static features 1.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Example: Solution of Quadratic Equations We want to solve for real values of x, for given values of a, b, and c. The value of x can be determined from.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Documentation Dr. Andrew Wallace PhD BEng(hons) EurIng
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming1 Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Newport Robotics Group 1 Tuesdays, 6:30 – 8:30 PM Newport High School Week 4 10/23/2014.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
1  lecture slides online
JAVA PROGRAMMING PART III. METHOD STATEMENT Form of method statement [ ] [static] ( [ ]) { } Example public static void main(String args[])
Chapter 3 Objects and Classes. Objects Object – a data type with structure, state, and operations to access and manipulate state - an instance of a class.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
CSE 1030: Implementing Static Features Mark Shtern.
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
The if-else statement. Introducing the if-else statement Programming problem: Re-write the a,b,c-formula program to solve for complex number solutions.
Defining Your Own Classes II
Information and Computer Sciences University of Hawaii, Manoa
The need for Programming Languages
More Sophisticated Behavior
Data Structures and Algorithms revision
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Static data members Constructors and Destructors
Yanal Alahmad Java Workshop Yanal Alahmad
Solving quadratics methods
Lecture 17: Polymorphism (Part II)
Tirgul 7.
Copyright © 2017, 2013, 2009 Pearson Education, Inc.
CS 302 Week 11 Jim Williams, PhD.
Introduction to javadoc
CMSC 202 Static Methods.
Computer Science II Exam 1 Review.
Overloading and Constructors
Introduction to Java Programming
slides created by Ethan Apter
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Chapter 1: Computer Systems
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Building Java Programs
slides created by Ethan Apter
Basics of OOP A class is the blueprint of an object.
Introduction to javadoc
Lecture 18: Polymorphism (Part II)
Java Programming Language
Bell work Describe what the following graphs may look like 2x^7 +3x^2
Outline Software Development Activities
slides created by Ethan Apter and Marty Stepp
First Semester Review.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Tirgul 4 Reference variables Method overloading The keyword “this” Javadoc Interface vs. implementation Bottom-up design

Primitive types Primitive variables correspond to memory locations which store their current value 200 201 202 i 5 int i = 5; int j = i; i = 6; memory addresses 200 201 202 i j 5 200 201 202 i j 6 5

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); 200 201 202 300 301 302 . . . 300 1 2 99 d _day _month _year

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); 200 201 202 d1 d2 300 . . . 300 301 302 1 2 99 _day _month _year 400 401 402 400 d1.setYear(88); 200 201 202 300 301 302 400 401 402 1 2 99 _day _month _year . . . . . . 300 400 1 2 88 d1 d2 _day _month _year

Different references to the same object Date d1 = new Date(1,2,99); Date d2 = d1; 200 201 202 d1 d2 300 . . . 300 301 302 1 2 99 _day _month _year 400 401 402 d1.setYear(88); 200 201 202 d1 d2 300 . . . 300 301 302 1 2 88 _day _month _year 400 401 402

Comparing references Date d1 = new Date(1,2,99); if (d1 == d2) System.out.print(“Same date”); else System.out.print(“Different”);

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

Comparing objects Date d1 = new Date(1,2,99); if (d1.equals(d2)) System.out.print(“Same date”); else System.out.print(“Different”);

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

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)

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

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

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;

Javadoc You must write documentation comments (starting with /**) for ALL classes, data members, and methods (public and private) For methods, include @param and @return tags Create HTML documentation from your sources: javadoc –private –d doc *.java This command should execute with no warnings/errors!

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

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)

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…

Complex numbers A complex number z may be described in (at least) two ways: Cartesian (x,y) Polar (φ,r)

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

Class design QuadDriver QuadSolver QuadSolution Complex

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

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

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

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

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 }

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

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

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

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

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

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

Class design QuadDriver QuadSolver QuadSolution Complex

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;

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;

Default constructor /** Construct a QuadSolution indicating that all numbers solve the equation */ public QuadSolution() { _type = TYPE_INFINITY; _sol1 = _sol2 = null; }

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;

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

Class design QuadDriver QuadSolver QuadSolution Complex

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

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

Class design QuadDriver QuadSolver QuadSolution Complex

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