Download presentation
Presentation is loading. Please wait.
1
1 Tirgul no. 4 Topics covered: H Defining classes H Documentation using javadoc H The computer memory during program execution.
2
2 Defining New Classes /* * This is a basic date object. For now it cannot do anything * except hold the initial date it is given in creation. */ public class Date { private int day; // the day in month, an integer variable private int month; private int year; /* * This is a constructur. This function is called when a new * object of type Date is created. It receives three parameters * that define the date. Note that the parameters are * assumed to be valid. */ public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; }
3
3 Using the Class We Wrote /* * This is a small application that shows how to use Date objects. */ public class DateTest { /* * This is a special method. If this class is run by java then the * excecution is started here. */ public static void main(String[] args) { Date d1; // declare a variable that refers to a Date object. // create a new Date objecet with the date 23/6/1997. // and make 'd' refer to it. d1 = new Date(23, 6, 1997) ; // we can also declare a variable and create // the object in one line: Date d2 = new Date(14, 4, 1998); }
4
4 Extending the Classes Functionality /* * This is a basic date object. For now it cannot do anything * except hold the initial date it is given in creation. */ public class Date { private int day; // the day in month, an integer variable private int month; private int year; /* * Same as previous example. */ public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } /** * This method prints the date to standard output. */ public void print() { System.out.println(day + "." + month + "." + year); }
5
5 Get and Set methods /* * The following methods are used to set and get the values of private * fields of the object. */ /* * set the value of the day. */ public void setDay(int newDay) { day = newDay; } /* * return the current day in the month. */ public int getDay() { return day; } /* * The setMonth(), getMonth(), setYear(), getYear() methods * are similar. */
6
6 Using Our Class public class DateTest { public static void main(String[] args) throws Exception { Date d1 = new Date(12, 11, 1997); Date d2 = new Date(1, 1, 1998); int day; System.out.print("the date d1 is: "); // don't move to next line d1.print(); // ask d1 to print itself System.out.print("the date d2 is: "); d2.print(); System.out.print("Please enter a new day for d1: "); day = EasyInput.readInt(); d1.setDay(day); // change d1's day. d2 is unchanged. // print again System.out.print("the date d1 is: "); // don't move to next line d1.print(); // ask d1 to print itself System.out.print("the date d2 is: "); d2.print(); }
7
7 Circle Class public class Circle { private double centerX; // the center of the circle private double centerY; private double radius; // the radius of the circle public Circle(double x, double y, double radius) { centerX = x; centerY = y; this.radius = radius; } public boolean isIn(double x, double y) { //use the Math object's power and square root methods to do //the calculation. double dist = Math.sqrt(Math.pow((centerX-x), 2.0) + Math.pow((centerY - y), 2.0)); // now check if point is in circle or not if (dist <= radius) { return true; } else { return false; }
8
8 Using our Circle Class public class PointInCircle { public static void main(String[] args) throws Exception{ double x,y; double radius; //read input from user and create circle System.out.print("Enter the circle center (x y): "); x = EasyInput.readDouble(); y = EasyInput.readDouble(); System.out.print("Enter the circle radius: "); radius = EasyInput.readlnDouble(); Circle cir = new Circle(x,y,radius); System.out.print("Enter X and Y coordinates (use space):"); x = EasyInput.readDouble(); y = EasyInput.readlnDouble(); if(cir.isIn(x,y)) { System.out.println("The point is in the circle"); } else { System.out.println("The point is not in the circle"); }
9
9 Javadoc (from sun’s javadoc documentation) Javadoc parses the declarations and documentation comments in a set of Java source files and produces a corresponding set of HTML pages describing (by default) the public and protected classes, inner classes, interfaces, constructors, methods, and fields. You can include documentation comments in the source code, ahead of declarations for any entity (classes, interfaces, methods, constructors, or fields). These are also known as Javadoc comments, and the text must be written in HTML, in that they should use HTML entities and can use HTML tags. How to run: javadoc MyClass.java The result includes several HTML files. We are only interested in the file MyClass.html.
10
10 Javadoc (cont.) A doc comment consists of the characters between the characters /** that begin the comment and the characters */ that end it. Javadoc parses special tags when they are embedded within a Java doc comment. These doc tags enable you to autogenerate a complete, well-formatted API from your source code. Important Javadoc tags: @author - author of code. @param - parameter description. @return - return value description. Example: /** * This method receives the new circle radius. * @param radius new circle radius. */ public setRadius(double radius) { this.radius = radius; }
11
11 Example of javadoc documentation /** * The Point class represents a 2-dimensional integral point. * @author Ziv Yaniv */ public class Point { private int x; // x-coordinate of this point private int y; // y-coordinate of this point /** * Construct a new point with the specified x y coordinates. * @param x The x coordinate. * @param y The y coordinate. */ public Point(int x, int y) { this.x = x; this.y = y; } /** * Return the x-coordinate of this point. */ public int getX() { return x; } /** * Set the x-coordinate of this point to be the given value. * @param newX The new x-coordinate. */ public void setX(int newX) { x = newX; }
12
12
13
13 Heap Stack Data Text Memory Structure of a Program When a program is loaded into memory it loads 4 memory segments: Text – is the program’s machine code, which contains all the program’s code after it has been compiled.
14
14 Heap Stack Data Text Memory Structure of a Program (contd.) Data – is a memory segment that contains constants etc. Stack – a.k.a (Runtime Stack) – a segment that contains frames – where each frame represents a call to a method in the program. Notice that it works as a LIFO (last in first out).
15
15 Heap Stack Data Text Memory Structure of a Program (contd.) Heap – The segment that contains all the dynamically alocated memory – in our case all of the objects! When using the operator ‘new’ and calling an object’s constructor the object is created in the Heap and a ref to it is returned to the desired ref within the stack. Ref’s that are declared and initialized in one of the frames in the stack, usually point to objects that exist within the heap.
16
16 date1ch=97number= main Data Text Date | day=13 | month=3| year=2000 Stack frame Object in Heap Java Types Primitive Types float, double long, int, short, byte char boolean Basic types are created by Declaring a variable: int number; char ch=‘a’; “number” and “ch” both reside in the Stack. Objects Objects are created by Declaring a reference and calling a constructor: Date date1= new Date(12,3,2000); date1 is a ref that exists in the Stack. It refers to a Date object that is located in the heap.
17
17 A java program A java program is a set of objects, where at least one of the objects has a method called ‘main’. Running a program means executing the commands which appear in the ‘main’ method. The ‘main’ method is usually comprised of calls to constructors, creating a set of objects and then sending them messages. Example: Let’s assume that class A holds the following main method decleration: Public static void main(String[] args){ // call to a constructor function of Date: Date date1; date1= new Date(3,13,2000); date1.setDay(15); … } The first method evoked when the program is run is the “main” method. A frame within the Stack is created and main begins to execute.
18
18 The first command in the main function is a call to a constructor of Date. Another frame is created in the stack for the constructor and the control of the program now passes to it. tempdate() main()date1 Data Text Date | day=13 | month=3| year=2000 Stack frames Heap The constructor executes to its end and when done its frame is popped out of the Stack and the control returns to the “main” method. A java program (contd.)
19
19 main()date1 Data Text Date | day=13 | month=3| year=2000 Heap Stack A java program (contd.) The programs memory would then look like:
20
20 Class Complex Example public class Complex { private double real; private double imaginary; Complex(double real,double imaginary) { this.real = real; this.imaginary = imaginary; } Complex(Complex other) { this.real = other.real; this.imaginary = other.imaginary; } public double getReal() { return real; } public double getImaginary() { return imaginary; }
21
21 Class Complex (contd.) public Complex add(Complex right) { double r,i; r = real + right.getReal(); i = imaginary + right.getImaginary(); return (new Complex(r,i)); } public Complex add(double val) { double r; r = real + val; return (new Complex(r,imaginary)); }
22
22 Class Complex (contd.) public Complex multiply(Complex right) { double r,i; r = (real * right.getReal()) - (imaginary * right.getImaginary()); i = (imaginary * right.getReal()) + (real * right.getImaginary()); return(new Complex(r,i)); } public Complex multiply(double scale) { double r,i; r = real * scale; i = imaginary * scale; return(new Complex(r,i)); } public String toString() { return new String(real + " + " + imaginary + "*i"); }
23
23 Class ComplexPair public class ComplexPair { private Complex first; private Complex second; public ComplexPair(Complex first, Complex second) { if(first != null) this.first = new Complex(first); if(second != null) this.second = new Complex(second); } public Complex getFirst() { if(first != null) return (new Complex(first)); return (null); } public Complex getSecond() { if(second != null) return (new Complex(second)); return (null); }
24
24 public class QuadSolution { private int numberOfSolutions; private Complex solution1; private Complex solution2; public QuadSolution(int solNum,Complex solution1,Complex solution2) { numberOfSolutions = solNum; this.solution1 = solution1; this.solution2 = solution2; } public int numSolutions() { return numberOfSolutions; } public String toString() { String result = new String(solution1.toString()); if(numberOfSolutions == 2) result = result.concat("\n" + solution2.toString() + "\n"); return result; }
25
25 public Complex getSolution(int solution) { switch(solution) { case 1: return solution1; case 2: if(numberOfSolutions == 1) { System.err.println("QuadSolution Error : trying to access non" + "existant solution"); return null; } else return solution2; default: System.err.println("QuadSolution Error : trying to access illegal" + "solution number (legal values are 1,2)."); return null; } A problem here? (Aliasing)
26
26 public class MyMath { //Assumption : only one coefficient a or b may be zero. public QuadSolution solveQuadratic(double a,double b,double c) { int solNum; Complex solution1=null; Complex solution2=null; double disc; if(a==0) { solNum=1; solution1 = new Complex(-c/b,0.0); } else { disc = b*b - 4*a*c; if(disc==0) { solNum=1; solution1 = new Complex(-b/(2*a),0); } else if(disc<0) { disc = Math.sqrt(-disc); solution1 = new Complex(-b/(2*a),disc/(2*a)); solution2 = new Complex(-b/(2*a),-disc/(2*a)); solNum=2; } else { disc = Math.sqrt(disc); solution1 = new Complex((-b+disc)/(2*a),0); solution2 = new Complex((-b-disc)/(2*a),0); solNum=2; } return new QuadSolution(solNum,solution1,solution2); }
27
27 Date d1,d2; d1= new Date(1,1,1999); d2 = new Date(1,1,1999); d1 1,1,1999 d2 1,1,1999 Date d1,d2; d1= new Date(1,1,1999); d2 = d1; d1 1,1,1999 d2 Memory/Aliasing
28
28 Date d1,d2; d1= new Date(1,1,1999); d2 = new Date(1,1,1999); if(d1 == d2) System.out.println(“same date”); Date d1,d2; d1= new Date(1,1,1999); d2 = d1; if(d1 == d2) System.out.println(“same date”); Which program prints “same date” ? Why? Is this what we really want? Memory (cont.)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.