BITS Pilani, Pilani Campus
BITS PilaniPilani Campus
Dr. Yashvardhan SharmaCSIS Dept., BITS-Pilani
IS F213 Object Oriented Programming
BITS Pilani, Pilani Campus
Objects as Parameters To Methods
1. Objects are always passed by reference w.r.t its instance field values i.e state of the object. ( State of object Can be changed by using the same reference variable )
2. If you are changing the values of instance fields by using same reference variable then changes will be reflected in the calling program. [ That’s what we mean by callByReference ]
3. Objects are always passed by value w.r.t. its reference. The Called Method can not change the passed parameter reference to some another object . The called method if tries to change the reference of passed parameter then that change remains local only and will not be reflected to calling method.
BITS Pilani, Pilani Campus
class A{int a,b;A(int a,int b){this.a =a; this.b=b;}void show(){System.out.println("a="+a);System.out.println("b="+b);}
Example1 (Objects as parameters to methods)
void changeContents(A other){other.a = 20;other.b = 100;}void changeReference(A other){other = new A(-10,-20);other.a = 20;other.b = 100;}} // End of class A
BITS Pilani, Pilani Campus
class objref{public static void main(String args[]){A a1=new A(40,50);a1.show();a1.changeReference(a1); a1.show();}}
Objects as Parameters Methods
E:\New Folder\Java>java objrefa=40b=50a=40b=50
a1 40 50a b
BITS Pilani, Pilani Campus
class objref{public static void main(String args[]){A a1=new A(40,50);a1.show();a1.changeContents(a1);a1.show();}}
Objects as Parameters Methods
E:\New Folder\Java>java objrefa=40b=50a=20b=100
a1 40 50a b
other
changeContents(A other)Method does not change the reference for other
BITS Pilani, Pilani Campus
class greeter{String name;greeter(String name){this.name = name;}String sayHello(){return "Hello"+name+"!";}void copyNameTo(greeter other){other.name = this.name;} void copyGreeterTo(greeter other){other = new greeter(“Ram");}}
TEXT BOOK EXAMPLE
Changing other name value with this name value [ State Change] By Reference w.r.t State
Changing other reference to another greeter [ Reference Change] By value w.r.t to reference change
BITS Pilani, Pilani Campus
class greetertest{public static void main(String args[]){greeter worldgreeter = new greeter("World");greeter davegreeter = new greeter("Dave");System.out.println(worldgreeter.name);System.out.println(davegreeter.name);worldgreeter.copyNameTo(davegreeter);System.out.println(worldgreeter.name);System.out.println(davegreeter.name);greeter g1 = new greeter("KAMAL");greeter g2 = new greeter("SHARMA");System.out.println(g1.name);System.out.println(g2.name);g1.copyGreeterTo(g2);System.out.println(g1.name);System.out.println(g2.name);}}
BITS Pilani, Pilani Campus
class greeter{String name;greeter(String name) { this.name = name; }void setName(String name){this.name = name;}void copyNameTo(greeter other){other.name = this.name;}void copyLengthTo(int n){n = name.length();}
void copyGreeterTo(greeter other){other = new greeter("Pankaj Vyas");}void swapNames(greeter other){String temp = other.name;other.name = this.name;this.name = temp;}void swapReference(greeter other){greeter temp = other;other = this;this = temp;} }
TEXT BOOK PROBLEM 1.13, 1.14
this is final reference. Cannot be changed by methodswapReference
Cont…..
BITS Pilani, Pilani Campus
class greetertest{public static void main(String args[]){greeter g1 = new greeter("OOP");g1.setName("BITS");
greeter g2 = new greeter("KAMAL");g1.copyNameTo(g2);
}}
D:\Java1>javac greetertest.javagreetertest.java:34: cannot assign a value to final variable thisthis = temp;^1 error
Continue Problem……
BITS Pilani, Pilani Campus
class BOX{private double length,width,height;BOX(double l,double b,double h){length = l; width = b; height =h;}// Mutator Methodspublic void setLength(double l) { this.length = l;}public void setWidth(double b) { this.width = b; }public void setHeight(double h) { this.height = h;}// Accessor Methodspublic double getLength() { return this.length;}public double getWidth() { return this.width; }public double getHeight() { return this.height;}void showDimension(){System.out.println("Length:"+this.length);System.out.println("Width:"+this.width);System.out.println("Height:"+this.height);}
BITS Pilani, Pilani Campus
double area() { return 2 * (length * width + width*height + height*length);}double volume() { return length*width*height ;}
void swapBoxes(BOX b1, BOX b2){BOX temp = b1;b1 = b2;b2 = temp;}}// End of BOX
BITS Pilani, Pilani Campus
class BOXtest{public static void main(String args[]){BOX b1 = new BOX(10,40,60);BOX b2 = new BOX(20,30,80);BOX b3 = new BOX(100,200,300);
b1.showDimension();b2.showDimension();
b3.swapBoxes(b1,b2);
b1.showDimension();b2.showDimension();}}//End of Main
D:\java\bin>java BOXtestLength:10.0Width:40.0Height:60.0
Length:20.0Width:30.0Height:80.0
Length:10.0Width:40.0Height:60.0
Length:20.0Width:30.0Height:80.0
BITS Pilani, Pilani Campus
class BOXtest{public static void main(String args[]){BOX b1 = new BOX(10,40,60);BOX b2 = new BOX(20,30,80);BOX b3 = new BOX(100,200,300);
b1.showDimension();b2.showDimension();
// b3.swapBoxes(b1,b2);
BOX temp = b1;b1 = b2;b2 = temp;
b1.showDimension();b2.showDimension();}}//End of Main
D:\java\bin>java BOXtestLength:10.0Width:40.0Height:60.0
Length:20.0Width:30.0Height:80.0
Length:20.0Width:30.0Height:80.0
Length:10.0Width:40.0Height:60.0
BITS Pilani, Pilani Campus
Reading Inputs in Java
1. Use BufferedReader (Use io package [import java.io.*;])
throws IOException
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)));
String str = br.readLine(); int n = Integer.parseInt(str); float f = Float.parseFloat(str); double a = Double.parseDouble(str);
BITS Pilani, Pilani Campus
UML Representation for Class Point
Point
x: doubley: double
+getX() : double+getY() : double+setX(x: double) : void+setY(y: double) : void+equals(other : Point) : boolean+computeDistance(other : Point) : double+show() : void
class Point{double x; // x – coordinatedouble y; // y –coordinate
public double getX() { return x; }public double getY() { return y; } public void setX(double x) { this.x = x; }public void setY(double y) { this.y = y; }public boolean equals(Point other){return this.x == other. x && this.y == other.y ;} public double computeDistance(Point other){double a = (this.y – other.y) * (this.y – other.y);double b = this.x – other.x) * (this.x – other.x);return Math.sqrt(a+b); }
public void show(){S.O.P(“ x= “+x);S.O.P(“ y= “+y);}} End of Point Class
Attributes
Operations
BITS Pilani, Pilani Campus
Class PointTest
class PointTest{public static void main(String args[ ]){Point P1 = new Point();P1.show();Point P2 = P1;P2.show();System.out.println(P1.equals(P2));System.out.println(P1.computeDistance(P2));}// End of main() Method}// End of PointTest
BITS Pilani, Pilani Campus
OBJECT CONTAINMENT
• When one class contains instance of other class as its instance field then it is known as object containment.
• Object Containment defines one of the important concepts of UML known as composition or aggregation or a-part-of or has a relationship
Player Team Aggregation
Engine Car Composition
BITS Pilani, Pilani Campus
class Line{private Point x;private Point y; private double length;
Line(Point x,Point y){this.x = x;this.y = y;length = x.computeDistance(y);}
Line(double x1, double y1, double x2, double y2){x = new Point(x1,y1);y = new Point(x2,y2);length = x.computeDistance(y);}
Example Object Containment
Line class
Point Lineinstance variables of class Line
Constructor where Line can be created from two points
computeDistance() method of point class
Constructor where Line can be created from 4 double values
BITS Pilani, Pilani Campus
void show(){System.out.println("x="+x);System.out.println("y="+y);System.out.println("Length="+length);}// Introduce a method for computing slope} // End of Line class
Method for printing the values for x and y and length
BITS Pilani, Pilani Campus
E:\New Folder\Java>java LineDemox=Point@256a7cy=Point@720eeb
Length=25.612496949731394
class LineDemo{public static void main(String args[]){Point p1 = new Point();Point p2 = new Point(4,true);Point p4 = new Point(10,8);Point p5 = new Point(-10,-8);Line l2 = new (new Point(),new Point(3,5));Line l1 = new Line(p4,p5);l1.show();}}
Origin pointX =4 , Y =0X =10,Y =8X =-10,Y =-8
BITS Pilani, Pilani Campus
There are Four different uses of static keyword in java.1. static instance variables2. static methods3. static classes4. static blocks
Use of static keyword in Java
Note :static field/methods of a class can be accessed/referenced even withoutcreating the objects of that class [ Provided They are not static].
Syntax : <classname> . <fieldname> OR
<classname> . <methodname>
BITS Pilani, Pilani Campus
static instance variables/fields
• Static field/instance variables are allocated space in the heap area.
• Static field is just like a global variable for a class that is allocated memory once and all objects of that class share that common copy.
• For a static fields of any class, all the objects of that class share a common copy.
• Declaring an instance field as static makes it class variable that belongs to a whole class not an individual object.
• Any Field/Attribute/instance field of a class can be declared as static.
BITS Pilani, Pilani Campus
Example (Static Fields)
class circle{static double PI=3.14156; double radius; double area(){return PI * radius * radius;} double perimeter(){return 2*PI*radius;}} // End of circle class
Static Member
Non-static instance field
circle c1 = new circle();circle c2 = new circle();
c1 c2radius radius
PI = 3.14156
Memory Map
BITS Pilani, Pilani Campus
Example (Static Fields)
class A{static int a = 10; double b , c; ……….}
A a1 = new A();
A a2 = new A();
Memory Map
a1 a2b c b c
a=10
BITS Pilani, Pilani Campus
Static Methods
• static methods can use only static data• static methods can be called/accessed/referenced even without
creating the objects that class.• Syntax <class name> . < method name(parameter list)>• static method can not call non static methods.• Examples: Math.sqrt (all math functions)• Static method can declare local variables but from outside it can
access only static data(fields/methods)
BITS Pilani, Pilani Campus
class num{int a,b,c;static int d = 10;static double e = 20.56;num(int a,int b,int c){ this.a = a; this.b =b; this.c =c; }static int sum(int a1 , int b1){//System.out.println(“a=”+a+”b=”+b+”c=”+c);System.out.println(“d=”+d+”e=”+e);return 40;}
Static Method Example
a,b,c are non static fields and can not be accessed from a static method
non static instance fields
static instance fields
static method
BITS Pilani, Pilani Campus
static double sum(double a , double b){System.out.println(“d=”+d+”e=”+e);return 40.56;}static void pr(){System.out.println(“This is method pr”);}void print(){System.out.println(“This is method print”);pr(); // call to static method from a non static method ---- VaildSystem.out.println(“a=”+a+”b=”+b+”c=”+c);System.out.println(“d=”+d+”e=”+e);}}
BITS Pilani, Pilani Campus
class BOX{private double l,b,h; // Instance FieldsBOX(double a,double b,double c) { l=a;this.b=b;h=c;} // Constructorboolean isEqual(BOX other){if (this.l == other.l && this.b == other.b && this.h == other.h)return true;elsereturn false;}static boolean isEqual(BOX b1, BOX b2){if (b1.l == b2.l && b1.b == b2.b && b1.h == b2.h)return true;elsereturn false;}} // End of BOX class
BITS Pilani, Pilani Campus
class statictest{public static void main(String args[]){BOX b1 = new BOX(10,6,8);BOX b2 = new BOX(10,6,8);BOX b3 = new BOX(1,16,18);BOX b4 = new BOX(2,6,8);
System.out.println(b1.isEqual(b2));System.out.println(BOX.isEqual(b1,b2));System.out.println(b3.isEqual(b1,b2));System.out.println(b4.isEqual(b2));System.out.println(b4.isEqual(b4,b2));}}
D:\Java1>java statictesttruetruetruefalsefalse
BITS Pilani, Pilani Campus
1. final keyword in java can be used for following (i) class declaration (ii) variable declartion (iii) method decalaration
Use of final keyword in java
4. final keyword used with method definition means method can not be overridden by subclasses ( Makes sense
only when inheritance is used)
3. final keyword used with variable declaration makes it constant whose value cannot be changed. Final variables should be initialized to some values at the time of declaration.
2. final keyword for class means class cannot be inherited. Final classes can not have subclasses.
BITS Pilani, Pilani Campus
final class ABC{…………………………………..}class a extends ABC{……} // Wrong / Invalid
final int x = 40;final double x = 3.4;final double PI = 3.14
class ABC{…………………final void show()..}class a extends ABC{void show()……} // Wrong / Invalid
final classfinal instance
variable final methods
If it is declared as private final void show() then a can have methodvoid show()
BITS Pilani, Pilani Campus
final Keyword Example1class ABC{//final int a;final int a = 10;int b;double c;//final static int d;static int d;ABC(int x,double c,int d){ b=x; this.c = c; this.d =d ;}void show(){System.out.println("a="+a);System.out.println("b="+b);System.out.println("c="+c);System.out.println("d="+d);}}
Final field/variable should be initialized to some default value
BITS Pilani, Pilani Campus
class ABCDemo{public static void main(String args[]){ABC a1 = new ABC(10,8,5);ABC a2 = new ABC(-10,18,15);ABC a3 = new ABC(67,80.56,50);ABC a4 = new ABC(76,-6.45,95);a1.show(); }}
BITS Pilani, Pilani Campus
class A{final int a = 10;}class ABC{ public static void main(String args[]){A a1 = new A();final int a=10;System.out.println("a="+a);}}
final Keyword Example2
Instance field is declared as final
Local Variable is declared as final
BITS Pilani, Pilani Campus
final Object Reference
• You can declare any object reference as final• Declaring a Object reference as final does not mean
that Object’s state i.e attribute values can not be changed. We can change the values of attributes provided it is allowed.
• Declaring a Object reference as final makes the reference itself as final and it can not point to any other object.
BITS Pilani, Pilani Campus
final Object reference Example
class circle{double radius;circle(double radius){this.radius = radius;}double getRadius(){return radius;}void setRadius(double radius){this.radius = radius;}}// End of circle
final circle c1 = new circle(20);
c1.radius = 30;
circle c2 = new circle(30);
c1 = c2 WRONG
OK
c1 final object reference it can not point to another Object
BITS Pilani, Pilani Campus
Use of toString() Method
1. toString() method is defined by Object class(Supermost super class for all java classes
2. toString() defines the String form of any object.
3. Syntax :
public String toString() { …… }
4. Any class can override this method to provide String form of any object.
5. If it is not overridden then this method will be called from Object class.
BITS Pilani, Pilani Campus
class box{int l,b,h;box(int a,int b,int c){l=a;this.b=b;this.h=c;}void show(){System.out.println("length="+l);System.out.println(“Width="+b);System.out.println(“height="+h);}} // End of class box
BITS Pilani, Pilani Campus
class boxtest{public static void main(String args[]){box b1 = new box(10,20,30);box b2 = new box(4,5,6);System.out.println(10);System.out.println(10.25+10);System.out.println(b1);System.out.println(b2);}} // End of boxtest
?
BITS Pilani, Pilani Campus
/* Out PutE:\New Folder\Java>java boxtest1020.25box@256a7cbox@720eeb*/
Output GeneratedBy callingtoString() from Object
BITS Pilani, Pilani Campus
class box{int l,b,h;box(int a,int b,int c){l=a;this.b=b;this.h=c;}void show(){System.out.println("length="+l);System.out.println("Width="+b);System.out.println("height="+h);}public String toString(){return "Hello How are You";}} // End of box class
BITS Pilani, Pilani Campus
class boxtest1{public static void main(String args[]){box b1 = new box(10,20,30);box b2 = new box(4,5,6);System.out.println(10);System.out.println(10.25+10);System.out.println(b1);System.out.println(b2);}}
?
BITS Pilani, Pilani Campus
/* Out PutE:\New Folder\Java>java boxtest11020.25Hello How are YouHello How are You*/ Out Put generated By
toString() defined by box class