1 classes instructor: mainak chaudhuri [email protected]

37
1 Classes Instructor: Mainak Chaudhuri [email protected]

Upload: alisha-berry

Post on 12-Jan-2016

227 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

1

Classes

Instructor: Mainak [email protected]

Page 2: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

2

Classes• One class usually represents one type

of object– May contain its own member variables– May contain its own methods to operate

on the member variables

• Usually one class is defined in one Java file

• In the entire program exactly one class should contain a main method

Page 3: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

3

Example: Vehicle• Consider defining a class named Vehicle

– It has certain number of wheels– It has certain number of windows– It has certain number of seats– It has a speedpublic class Vehicle { // objects of public classes can be accessed // from anywhere (more acceptable and useful) public int wheels; public int windows; public int seats; public double speed;}

Page 4: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

4

Example: Vehicle• We have defined the class Vehicle• Now we need to use itclass VehicleExample { // This class need not be public as the sole purpose

of // this is to define the main method public static void main (String arg[]) { // Allocate an object of type Vehicle // Invoke default constructor Vehicle bicycle = new Vehicle(); Vehicle car = new Vehicle(); bicycle.wheels = 2; bicycle.windows = 0; bicycle.seats = 1; bicycle.speed = 5.0; // m/s // continued in next slide

Page 5: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

5

Example: Vehicle car.wheels = 4; car.windows = 5; car.seats = 5; car.speed = 20.0; }}• Observations

– Need a way to cleanly initialize the members

– Need methods to do something interesting with the members

Page 6: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

6

Example: Vehicle• User-defined constructorspublic class Vehicle { public int wheels; public int windows; public int seats; public double speed; public Vehicle (int wh, int wi, int se, double

sp) { wheels = wh; windows = wi; seats = se; speed = sp; }} // continued in the next slide

Page 7: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

7

Example: Vehicleclass VehicleExample { public static void main (String arg[]) { // Allocate an object of type Vehicle // Invoke constructor Vehicle bicycle = new Vehicle (2, 0,

1, 5.0); Vehicle car = new Vehicle (4, 5, 5,

20.0); }}

Page 8: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

8

Constructors• Used to initialize the member variables• Default constructor initializes these to

zero• Constructors are special type of methods

– Do not have a return type (not even void)– Must be public so that they can be accessed

from a different class– Cannot be static: static methods can be

invoked without attaching them to any object e.g., main; constructors by definition must be invoked for a particular object

Page 9: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

9

Example: Vehicle• Let us add one more method in the Vehicle

classpublic class Vehicle { public int wheels; public int windows; public int seats; public double speed; public Vehicle (int wh, int wi, int se, double

sp) { wheels = wh; windows = wi; seats = se; speed = sp; } // continued in the next slide

Page 10: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

10

Example: Vehicle public void print () { System.out.println (“Wheels: ” +

wheels); System.out.println (“Windows: ” +

windows); System.out.println (“Seats: ” +

seats); System.out.println (“Speed: ” +

speed); }} // end class

Page 11: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

11

Example: Vehicleclass VehicleExample { public static void main (String arg[]) { Vehicle bicycle = new Vehicle (2, 0,

1, 5.0); Vehicle car = new Vehicle (4, 5, 5,

20.0); System.out.println (“Bicycle:”); bicycle.print(); System.out.println(“Car:”); car.print(); }}

Page 12: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

12

Example: Vehicle• Let us give a name to the vehiclepublic class Vehicle { public int wheels; public int windows; public int seats; public double speed; public String name; public Vehicle (int wh, int wi, int se, double sp,

String s) { wheels = wh; windows = wi; seats = se; speed = sp; name = new String (s); } // continued in the next slide

Page 13: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

13

Example: Vehicle public void print () { System.out.println (name); System.out.println (“Wheels: ” +

wheels); System.out.println (“Windows: ” +

windows); System.out.println (“Seats: ” + seats); System.out.println (“Speed: ” +

speed); }} // end class// continued in the next slide

Page 14: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

14

Example: Vehicleclass VehicleExample { public static void main (String arg[]) { Vehicle bicycle = new Vehicle (2, 0,

1, 5.0, “Bicycle”); Vehicle car = new Vehicle (4, 5, 5,

20.0, “Car”); bicycle.print(); car.print(); }}

Page 15: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

15

Information hiding• Why classes?

– Idea is to encapsulate the “properties” of a class of objects into a compact structure

– Not to allow direct access to members of a class unless there is a good reason

– Allow access to members only through member methods: often called interfaces

– One object can talk to another only if there is a proper “channel” to do so: defines a natural hierarchy

• Upshot– Most member variables are private– Need methods to read/write from/to the

variables

Page 16: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

16

Information hiding• Consider a calculator

– Customer is often not concerned with the internal architecture

– Nor concerned about the algorithms implemented for addition, multiplication, etc.

– As long as a calculator offers interfaces to do addition, subtraction, etc., the customer is happy

– A calculator properly implemented as a class would allow you to hide these information

– Often such a class is said to define an abstract data type

Page 17: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

17

Designing an OO project• Some general and probably obvious

guidelines– Decide the components of your project– These will become the objects

• Decide if you need to further split the objects into finer objects (each object should be simple)

– Decide the constituents of each object• These will become the member variables

– Lay out the components on paper with relationships among them clearly shown

– The connections between the objects become the supported public methods

– Decide the private methods to fully implement the objects

Page 18: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

18

Example: polynomial• A polynomial is an aggregate of

algebraic terms• Each term has a coefficient and an

array of indices, one for each variable• Need three classes: an AlgebraicTerm

class, a polynomial class, and a top level class implementing main

Page 19: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

19

Example: polynomialpublic class AlgebraicTerm { private double coefficient; private int[] index; // General constructor public AlgebraicTerm (double coefficient,

int[] index) { int numVar = index.length; int i; this.index = new int[numVar]; for (i=0; i<numVar; i++) { this.index[i] = index[i]; } this.coefficient = coefficient; } // continued in next slide

Page 20: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

20

Example: polynomial // Special constructor for univariate // Note: method overloading public AlgebraicTerm (double

coefficient, int index) { this.coefficient = coefficient; this.index = new int[1]; this.index[0] = index; } // continued in next slide

Page 21: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

21

Example: polynomial public double Evaluate (double[] v) { int i; double value = coefficient; for (i=0; i<index.length; i++) { // Could say this.index[i] // But not needed value *= Math.pow(v[i], index[i]); } return value; } // continued in next slide

Page 22: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

22

Example: polynomial public AlgebraicTerm Add

(AlgebraicTerm aterm) { AlgebraicTerm rterm = null; if (checkConsistency (aterm)) { rterm = new AlgebraicTerm

(coefficient+aterm.GetCoefficient(), index);

} return rterm; } // continued in next slide

Page 23: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

23

Example: polynomial public double GetCoefficient () { return coefficient; }

public int[] GetIndex () { return index; } // continued in next slide

Page 24: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

24

Example: polynomial private boolean checkConsistency

(AlgebraicTerm aterm) { return (index.length ==

aterm.GetIndex().length); }} // end of AlgebraicTerm class; could

// make it richer

Page 25: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

25

Example: polynomialpublic class Polynomial { AlgebraicTerm [] terms; public Polynomial (double [] coefficient, int

[] index[], int numVar) { int nTerms = coefficient.length; int i; terms = new AlgebraicTerm[nTerms]; for (i=0; i<nTerms; i++) { terms[i] = new AlgebraicTerm

(coefficient[i], index[i]); } } // continued in next slide

Page 26: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

26

Example: polynomial public Polynomial (AlgebraicTerm [] t) { int nTerms = t.length; int i; terms = new AlgebraicTerm[nTerms]; for (i=0; i<nTerms; i++) { terms[i] = t[i]; // use carefully } } // continued in next slide

Page 27: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

27

Example: polynomial public void SetTerms (AlgebraicTerm[]

terms) { this.terms = terms; }

public AlgebraicTerm[] GetTerms () { return terms; } // continued in next slide

Page 28: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

28

Example: polynomial public double Evaluate (double[] v) { int nTerms = terms.length; int i; double value=0; for (i=0; i<nTerms; i++) { value += terms[i].Evaluate(v); } return value; } // continued in next slide

Page 29: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

29

Example: polynomial public Polynomial Add (Polynomial p) { Polynomial q = null; AlgebraicTerm[] aterms; int i; if (checkConsistency(p)) { // Assume ordered terms aterms = new AlgebraicTerm [terms.length]; for (i=0; i<terms.length; i++) { aterms[i] = terms[i].Add (p.GetTerms()[i]); } q = new Polynomial (aterms); } return q; } // continued in next slide

Page 30: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

30

Example: polynomial private boolean checkConsistency

(Polynomial p) { return (p.GetTerms().length ==

terms.length); }} // end of polynomial class; continued

in next slide

Page 31: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

31

Example: polynomialclass PolynomialExample { public static void main (String arg[]) { double coeff[] = {1, 2, 1}; int index[][] = {{2}, {1}, {0}}; double values[] = {-2}; Polynomial perfectQ = new Polynomial (coeff, index, 1); coeff[1] = -2; Polynomial perfectQ2 = new Polynomial (coeff, index, 1); Polynomial oneMoreQ = perfectQ.Add

(perfectQ2); // continued in next slide

Page 32: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

32

Example: polynomial swap (perfectQ, perfectQ2); System.out.println

(perfectQ.Evaluate(values) + “, ” + perfectQ2.Evaluate(values));

} // end main // following method doesn’t work /* private static void swap (Polynomial P1,

Polynomial P2) { AlgebraicTerm terms[] = P1.terms; P1.terms = P2.terms; P2.terms = terms; }*/ // continued in next slide

Page 33: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

33

Example: polynomial // Note that swap must be static

because // it is called by a static method private static void swap (Polynomial

P1, Polynomial P2) { AlgebraicTerm terms[] =

P1.GetTerms(); P1.SetTerms (P2.GetTerms()); P2.SetTerms (terms); }} // end class

Page 34: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

34

Announcements• Reminder: exam on 9th October• No tutorial and no lab next week• There is a class on 11th October

Page 35: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

35

String argument• Strings are objects

– Passed by reference value

• But strings cannot modified– Every string operation creates a new string

• Consider the following Java classclass StringTester { public static void main (String arg[]) { String s = “abcd”; ModifyString (s); System.out.println (“From main: ” + s); } // Continued in next slide

Page 36: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

36

String argument public static void ModifyString (String

s) { s += “e”; System.out.println (“From

ModifyString: ” + s); }}• The output is as followsFrom ModifyString: abcdeFrom main: abcd

Page 37: 1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in

37

String argument• The change is reflected only within

ModifyString– The concatenation operation creates a

new string and stores “abcde” in that– Assigns this new string to s– Addresses of s before and after the

concatenation are different– Original string s remains unchanged with

contents “abcd”