Lec 4

download Lec 4

of 34

  • date post

    18-Jan-2015
  • Category

    Documents

  • view

    42
  • download

    0

Embed Size (px)

description

 

Transcript of Lec 4

  • 1. IS F213 Object OrientedProgrammingBITS Pilani, Pilani CampusBITS PilaniPilani CampusDr. Yashvardhan SharmaCSIS Dept., BITS-Pilani

2. BITS Pilani, Pilani CampusExampleclass test1{public static void main(String args[]){byte b = 24;byte b1 = 678;char x = 45;char y = 70000;char y1 = -25;short x1 = 238999;float f = 678.45;double f1 = 56.67;}}D:javabin>javac test1.javatest1.java:6: possible loss of precisionfound : intrequired: bytebyte b1 = 678;^test1.java:8: possible loss of precisionfound : intrequired: charchar y = 70000;^test1.java:9: possible loss of precisionfound : intrequired: charchar y1 = -25;^test1.java:10: possible loss of precisionfound : intrequired: shortshort x1 = 238999;^test1.java:11: possible loss of precisionfound : doublerequired: floatfloat f = 678.45;^5 errors 3. BITS Pilani, Pilani CampusExample 2In C In Javaint a=10;if(10)printf("Hello");elseprintf("Hi");}OUTPUTHelloint a=10;if(10)S.O.P("Hello");elseS.O.P("Hi");}OUTPUTD:javabin>javac test100.javatest100.java:6: incompatible typesfound : intrequired: booleanif(a)^1 error 4. BITS Pilani, Pilani CampusExample 3% Operatorclass test101{public static void main(String args[]){int a=100, b=90;System.out.println(a%b);double a1= 10.56, b1 =4.67;System.out.println(a1%b1);}}D:javabin>java test101101.2200000000000006 5. BITS Pilani, Pilani CampusExample 4>>,>class test103{public static void main(String args[]){int x = -1024;System.out.println(x>>2);System.out.println(x>2);}} D:javabin>java test103-256-40961073741568 6. BITS Pilani, Pilani CampusSystem.out.println() Prints/Displays output and shifts the printcontrol to new line (Similar printf(n) in C) Displays output only in String form If parameter to it is not in String form then itwill be converted to string form by internallycalling toString() + operator can be used to concatenate datafrom different types 7. Hello10301020Hello20is my ageBITS Pilani, Pilani CampusExamples System.out.println(Hello+10); System.out.println(10+20); System.out.println(10+20); System.out.println(Hello: +20+is my age);Note :+ opeartor is used for dual purpose addition,concatenation 8. BITS Pilani, Pilani CampusSystem.out.print() Prints/Displays output starting from thesame line (Similar printf() in C) Displays output only in String form If parameter to it is not in String form then itwill be converted to string form by internallycalling toString() + operator can be used to concatenate datafrom different types 9. BITS Pilani, Pilani CampusExamplesclass test104{public static void main(String args[]){System.out.print("Hello");System.out.print("I am fine");System.out.println(" It is OK");}}D:javabin>java test104HelloI am fine It is OK 10. BITS Pilani, Pilani CampusExample 2class test105{public static void main(String args[]){System.out.print("Hello");System.out.print("I am fine");System.out.println(" It is OK");System.out.println(" It is OK Again");}}D:javabin>java test105HelloI am fine It is OKIt is OK Again 11. BITS Pilani, Pilani CampusDEFINING A CLASSSYNTAX [/] [static>] class [extends ] [implements .]{Member Variable declarations /Instance field declarations;Member Method Definitions;}ClassBody :1. package private or public for outer classes2. private , public , protected, package private for inner classes : class definition is final and can not be extended by sub classes.final class can not have sub classes : static keyword can only be applied for inner classes.Outer classes can not be static. : abstract keyword specifies that class is abstract. 12. BITS Pilani, Pilani CampusInstance Variable Declaration Syntax [] [] variable name = [value];where can be private, public, protected or by default friendly can be any primitive type or class type or interface type;Method Declaration Syntax [][ ][] [abstract] methodname( argument list ) [throws exceptiontype1..exceptiontype n]{.. Method Body}Where can be private, public, protected or by default friendly can be any primitive type or class type or interface type;Note :Default Access is always friendly. i.e. inside the package 13. BITS Pilani, Pilani CampusVisibility of fieldsAccessModifiersAccessLocationpublic protected Friendly[packageprivate]privateSame Class Yes Yes Yes Yessub classes inYes Yes Yes Nosame packageOther Classes inSame packageYes Yes Yes NoSubclasses inother packagesYes Yes No NoNon-subclassesin other packagesYes No No No 14. BITS Pilani, Pilani CampusClass Examples1.class xyz{ .. } // class is defined with friendly access2.public class abc{ ...} // class is defined with public access.Note :public classes should be written in the same file as name of class.public class abc should be written in file named abc.java.In a single source file only one class can be named with public access.3. final class xyz{ }final class means you can not create sub classes of the final class.class abc extends xyz{ .} is wrong. 15. BITS Pilani, Pilani CampusClass Examples4.abstract class xyz{ .. } // class is defined with friendly access(i) abstract classes needs to be subclassed.(ii) You can not create instances of abstract classes.xyz x1 = new xyz(); -------- Wrong Statement.abstract class abc{int a =10;float b = 20;abstract void show() ; // abstract method} 16. BITS Pilani, Pilani CampusExercise 1Define a class which encapsulates a point in 2 dimensional space. It has following membersX & Y coordinate values.It supports following operations(i) Individual operation for setting the values for Xand Y coordinates(ii) Computing the distance between two points(iii) Checking two points for equality [ Two points areequal if they have same values for X and Ycoordinates](iv) Method for translating the values for X and Y 17. BITS Pilani, Pilani CampusUML Representation for Class PointPointx: doubley: doubleAttributes+getX() : double+getY() : double+setX(x: double) : void+setY(y: double) : void+equals(other : Point) : boolean+computeDistance(other : Point) : double+show() : voidclass Point{double x; // x coordinatedouble y; // y coordinatepublic 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 ClassOperations 18. BITS Pilani, Pilani CampusClass PointTestclass 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 19. BITS Pilani, Pilani CampusHow to Create an Instance of a class(Creating Objects)Objects are always created/constructed/instantiated dynamicallyusing new opeartor.Syntax : = new ConstructorMethod();Constructor Method Method having same name as name of classExamples :BOX b1 = new BOX(); // Valid iff constructor is unparametrizedBOX b2 = new BOX(10,6,8); // Valid iff constructor is parametrized 20. BITS Pilani, Pilani CampusObject Creation ExamplesBOX b1 = new BOX();BOX b2 = b1;b1b2b2 is just another reference for the same objectBOXl b hONLY ONE OBJECT IS CREATED IN ABOVE STATEMENTS 21. BITS Pilani, Pilani CampusHow to Access Class members1. Private members of a class are only visible inside class body.2. Protected members have package scope and are accessible tosubclasses in other packages as well.3. private protected members are only accessible to subclasses in samepackage or other package. [Does not have Package Scope]4. public fields/methods are accessible from every where.5. Every access to public or friendly access fields of class is only throughobjects of that class. (Except static fields which are accessible throughclass name)Syntax.. ;.; 22. BITS Pilani, Pilani Campusclass Rectangle{int length;int width;void setData(int l,int w){length = l;width = w;}void printSides(){System.out.println("Length is:"+length);System.out.println("Width is:"+width);}int area() { return length * width ;}} // End of classclass RectangleTest{public static void main(String args[]){Rectangle r1 = new Rectangle();r1.setData(10,8);r1.printSides();System.out.println("Area ="+r1.area());Rectangle r2 = new Rectangle();r1.setData(100,80);r1.printSides();System.out.println("Area ="+r2.area());}} // End of class/* OutputE:New FolderJava>java RectangleTestLength is:10Width is:8Area =80Length is:100Width is:80Area =0*/Example 23. BITS Pilani, Pilani Campusclass Rectangle{int length;int width;void setData(int l,int w){length = l;width = w;}void printSides(){System.out.println("Length is:"+length);System.out.println("Width is:"+width);}int area() { return length * width ;}}class RectangleTest{public static void main(String args[]){Rectangle r1 = new Rectangle();r1.printSides();r1.setData(10,8);System.out.println("Area ="+r1.area());Rectangle r2 = new Rectangle();r2.printSides();r1.setData(100,80);System.out.println("Area ="+r2.area());}}/*E:New FolderJava>java RectangleTestLength is:0Width is:0Area =80Length is:0Width is:0Area =0*/ 24. BITS Pilani, Pilani CampusConstructors1. If a class has any method with the same name as its class then it isconstructor method for that class2. Used to initialize the objects upon creation3. In the absence of constructor method we have to specifically add amethod for object initialization4. If no constructor is defined for the class then a default constructor isprovided by Java run time environment (Without Parameters).5. Constructor method has no return type not even void.6. Code written inside constructor method is automatically executed forevery object creation of that class. 25. BITS Pilani, Pilani CampusTypes of Constructors1. Unparametrized Constructor2. Parametrized Constru