Download presentation
Presentation is loading. Please wait.
1
1 Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
2
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
3
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 speed public 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; }
4
4 Example: Vehicle We have defined the class Vehicle Now we need to use it class 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
5
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
6
6 Example: Vehicle User-defined constructors public 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
7
7 Example: Vehicle class 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); }
8
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
9
9 Example: Vehicle Let us add one more method in the Vehicle class public 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
10
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
11
11 Example: Vehicle class 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(); }
12
12 Example: Vehicle Let us give a name to the vehicle public 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
13
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
14
14 Example: Vehicle class 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(); }
15
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
16
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
17
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
18
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
19
19 Example: polynomial public 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
20
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
21
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
22
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
23
23 Example: polynomial public double GetCoefficient () { return coefficient; } public int[] GetIndex () { return index; } // continued in next slide
24
24 Example: polynomial private boolean checkConsistency (AlgebraicTerm aterm) { return (index.length == aterm.GetIndex().length); } } // end of AlgebraicTerm class; could // make it richer
25
25 Example: polynomial public 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
26
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
27
27 Example: polynomial public void SetTerms (AlgebraicTerm[] terms) { this.terms = terms; } public AlgebraicTerm[] GetTerms () { return terms; } // continued in next slide
28
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
29
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
30
30 Example: polynomial private boolean checkConsistency (Polynomial p) { return (p.GetTerms().length == terms.length); } } // end of polynomial class; continued in next slide
31
31 Example: polynomial class 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
32
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
33
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
34
34 Announcements Reminder: exam on 9 th October No tutorial and no lab next week There is a class on 11 th October
35
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 class class StringTester { public static void main (String arg[]) { String s = “abcd”; ModifyString (s); System.out.println (“From main: ” + s); } // Continued in next slide
36
36 String argument public static void ModifyString (String s) { s += “e”; System.out.println (“From ModifyString: ” + s); } The output is as follows From ModifyString: abcde From main: abcd
37
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”
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.