An introduction to Java II Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 4-1 Java: Generalities A little bit of History Goals and characteristics First programs jvo@ualg.pt José Valente de Oliveira 3-2 1
Classes and objects Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 4-3 Recall: What s an object? An object is like a black box: Internal details are hidden. An object represents a concrete entity of the problem domain, that handles a specific task Examples include: Tangible things as cars, bank accounts Roles as employee, boss,... Interactions as contract, sale,... jvo@ualg.pt José Valente de Oliveira 4-4 2
Problem: Distance between points within the first quadrant Sample input Sample output 1 1 3 4 2 jvo@ualg.pt José Valente de Oliveira 4-5 Problem: Distance between points within the first quadrant Write a program that, given any two points with non-negative coordinates,compute the integer part of the distance between then Let the coordenates of points A, and B be (xa, ya) e (xb, yb) respectively, the distance d between A and B is given by: 2 2 d = ( xa xb ) + ( ya yb ) Input Input has two rows. The first has two integers XA, YA, representing the coordinates of point A. The second line is similar to the first one,representing the coordinates of point B. 0 <= XA <= 1000, 0 <= YA <= 1000 Output The output is an integer denoting the integer part of the distance between the input points Sample input Sample output 1 1 3 4 2 jvo@ualg.pt José Valente de Oliveira 4-6 3
Objects: a definition, again An object can be seen as an abstraction which represents an entity with interest for the problem to solve. An object has: State Behaviour Identity jvo@ualg.pt José Valente de Oliveira 4-7 Objects: a definition, again An object can be seen as an abstraction which represents an entity with interest for the problem to solve. An object has: State Behaviour Identity Point A is an object with: -State: Coordinates (X A =1, Y A =1) - Behaviour: computes the distance between itself and another point - Identify: Object point A is diferent from any other object jvo@ualg.pt José Valente de Oliveira 4-8 4
What s a class? A class can be seen as a description of a set of objects sharing the same data structure (not the same data) and the same behaviour (functions) jvo@ualg.pt José Valente de Oliveira 4-9 Examples of classes and their objects Class Objects Data Typical functions Point (0, 0) (4.5; 7.2) x=0; y =0 x=4,5; y=7.2 BankAccount account1 Balance=0 Number=12 Fraction ½ Numerator = 1 Denominator =2 dist Transfer withdraw sum jvo@ualg.pt José Valente de Oliveira 4-10 5
The simplest class implementation /** @version 0.0 */ // Bad code usefull for motivation only int x, y; double dist(point p) { jvo@ualg.pt José Valente de Oliveira 3-11 Control of visibility /** @version 1.0 */ private int x, y; public double dist(point p) { Three keywords: - public - private - protected jvo@ualg.pt José Valente de Oliveira 3-12 6
Sintaxe jvo@ualg.pt José Valente de Oliveira 3-13 Sintaxe jvo@ualg.pt José Valente de Oliveira 3-14 7
Sintaxe for attributes jvo@ualg.pt José Valente de Oliveira 3-15 Sintaxe for attributes, illustrated /** @version 1.0 */ private int x, y; public double dist(point p) { jvo@ualg.pt José Valente de Oliveira 3-16 8
Sintaxe for methods jvo@ualg.pt José Valente de Oliveira 3-17 Sintaxe for methods, illustrated @version 1.0 private int x, y; public double dist(point p) { int dx; dx = x p.getx(); int dy = y p.gety(); return Math.sqrt(dx*dx+dy*dy); jvo@ualg.pt José Valente de Oliveira 3-18 9
Constructors jvo@ualg.pt José Valente de Oliveira 4-19 Check point: what s common in these classes? class Person { private String name; public Person(String s) { name = s; class X { public X() { private int x, y; public Point(int x, int y) { setx(x); sety(y); 10
Constructors private int x, y; public Point(int x, int y) { setx(x); sety(y); Constructors initializes an object - Reserve memory to object data (instance variables) - Return a reference to that memory area // Client code Point p; // variable declaration p = new Point(1, 2); // calls the constructor Constructor A constructor is called whenever a object is created, using the keyword new A constructor has the following characteristics: - It has the same name as the class - It does not have a return type (not even void!) // Client code Point p; // variable declaration p = new Point(1, 2); // calls the constructor 11
Default constructor If the class does not define any constructor, the compiler will provide a default (or nonargument) constructor. Default constructor allows for instance variable default initialization If the class define a contructor (any constructor) the compiler will not provide a default constructor. Default variable initializations Local variables are not automatically initialized Instance variables are automatically initialized: boolean types are initialized to false Other primitives are initialized to the zero of their type Class types are initialized to null It is a good programming practice to explicitly initialize instance variables within a constructor 12
Default constructor example // AVOID: Used for motivation only private int x, y=1024; public int getx() {return x; public int gety() {return y; public class Main { public static void main(string[] args) { Point p = new Point(); System.out.println(p.getX()); System.out.println(p.getY()); Default constructor example /** @version 1.0 */ private int _x_, _y_; public Point(int x, int y) { setx(x); sety(y); public int getx() { return _x_; public int gety() { return _y_; public void setx(int x) { if (x<0) System.exit(1); _x_ = x; public void sety(int y) { public class Main { public static void main(string[] args) { Point p = new Point(); System.out.println(p.getX()); System.out.println(p.getY()); 13
Explicit default constructor /** @version 1.1 */ private int _x_, _y_; public Point() { public Point(int x, int y) { setx(x); sety(y); // Explicit default constructor an improved version /** @version 2.0 */ private int _x_, _y_; public Point() { _x_ = 0; _y_ = 0; public Point(int x, int y) { setx(x); sety(y); // 14
References In Java a variable contains either a value of primitive data type or a reference. If the variable are primitive data types, assigning means copying the value resulting from the right expression to the contents of the variable on the left. In the example, int i, j =10; i=j; both i and j have independent storage spaces, that after assignment will have the same value jvo@ualg.pt José Valente de Oliveira 3-29 References Should a variable hold a reference, assigning means that the variable on the left will now refer to the object resulting from the evaluation of right expression. In the example: Point a, b = new Point(1, 2); a=b; a.setx(0); System.out.println(b.getX()); Both variables a, andb willreferbothtothesame object of the class Point jvo@ualg.pt José Valente de Oliveira 3-30 15
Argument passing In Java argument passing is allways done by value. The values of primitive data types are copied to the function formal parameters; for other types, what are copied are the references (not the objects themselves). This is equivalent to reference argument passing. jvo@ualg.pt José Valente de Oliveira 3-31 Method overloading Method overloading occurs when two or more methods within the same class have the same name To be valid, any two definitions of the method name must have different signatures A signature consists of the name of a method together with its parameter list Differing signatures must have different number and/or types of parameters 16
Method overloading When a name of a method is declared twice within the same class, the compiler views the second declaration as follows: - If the return type and the signature of both methods agree, methods are viewed as a duplicate; int mult (int a, float b) { // ; Int mult (int a, float b) { // ; //Error duplicate method - If the signature of both methods are equal but the return type are different, the second declaration is viewed as an error; float mult (int a, float b) { // ; Int mult (int a, float b) { // ; //Error - If signatures are different in the number and/or type of parameters, both methods are viewed as overloaded. float mult (int a, float b) { // ; float mult ( float a, float b) { // ; //OK Check point: what s the output? private int x,y; public void setx(int nx) { x = nx; public int getx() { return x; public class Check{ public static void main(string[] args) { Point origin = new Point(); Point B = origin; B.setX(1); System.out.println(origin.getX()); jvo@ualg.pt José Valente de Oliveira 3-34 17
Where are we so far? Java A little bit of history Goals and characteristics First programs Control of visibility Classes Sintaxe Initialization of objects: constructors References Method overloading (to be continued.) jvo@ualg.pt José Valente de Oliveira 3-35 18