370 likes | 387 Views
Learn about classes in Java programming, creating objects, member variables, methods, constructors, and information hiding concepts. Practice coding examples for better understanding.
E N D
Classes Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
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
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; }
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
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
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
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); } }
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
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
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
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(); } }
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
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
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(); } }
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
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
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
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
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
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
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
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
Example: polynomial public double GetCoefficient () { return coefficient; } public int[] GetIndex () { return index; } // continued in next slide
Example: polynomial private boolean checkConsistency (AlgebraicTerm aterm) { return (index.length == aterm.GetIndex().length); } } // end of AlgebraicTerm class; could // make it richer
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
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
Example: polynomial public void SetTerms (AlgebraicTerm[] terms) { this.terms = terms; } public AlgebraicTerm[] GetTerms () { return terms; } // continued in next slide
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
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
Example: polynomial private boolean checkConsistency (Polynomial p) { return (p.GetTerms().length == terms.length); } } // end of polynomial class; continued in next slide
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
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
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
Announcements • Reminder: exam on 9th October • No tutorial and no lab next week • There is a class on 11th October
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
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
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”