Lec 4

34
BITS Pilani, Pilani Campus BITS Pilani Pilani Campus Dr. Yashvardhan Sharma CSIS Dept., BITS-Pilani IS F213 Object Oriented Programming

description

 

Transcript of Lec 4

Page 1: Lec 4

BITS Pilani, Pilani Campus

BITS PilaniPilani Campus

Dr. Yashvardhan SharmaCSIS Dept., BITS-Pilani

IS F213 Object Oriented Programming

Page 2: Lec 4

BITS Pilani, Pilani Campus

Exampleclass 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:\java\bin>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

Page 3: Lec 4

BITS Pilani, Pilani Campus

Example 2

int a=10;if(10)printf("Hello");elseprintf("Hi");}

OUTPUT

Hello

int a=10;if(10)S.O.P("Hello");elseS.O.P("Hi");}OUTPUTD:\java\bin>javac test100.javatest100.java:6: incompatible typesfound : intrequired: booleanif(a) ^1 error

In C In Java

Page 4: Lec 4

BITS Pilani, Pilani Campus

Example 3% Operator

class 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:\java\bin>java test101101.2200000000000006

Page 5: Lec 4

BITS Pilani, Pilani Campus

Example 4 >>,<<,>>>

class test103{public static void main(String args[]){int x = -1024;System.out.println(x>>2);System.out.println(x<<2);System.out.println(x>>>2);}} D:\java\bin>java test103

-256-40961073741568

Page 6: Lec 4

BITS Pilani, Pilani Campus

System.out.println()

• Prints/Displays output and shifts the print control to new line (Similar printf(“\n”) in C)

• Displays output only in String form• If parameter to it is not in String form then it

will be converted to string form by internally calling toString()

• + operator can be used to concatenate data from different types

Page 7: Lec 4

BITS Pilani, Pilani Campus

Examples

• 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

Hello1030

1020

Hello20is my age

Page 8: Lec 4

BITS Pilani, Pilani Campus

System.out.print()

• Prints/Displays output starting from the same line (Similar printf() in C)

• Displays output only in String form• If parameter to it is not in String form then it

will be converted to string form by internally calling toString()

• + operator can be used to concatenate data from different types

Page 9: Lec 4

BITS Pilani, Pilani Campus

Examples

class test104{public static void main(String args[]){System.out.print("Hello");System.out.print("I am fine");System.out.println(" It is OK");}}

D:\java\bin>java test104HelloI am fine It is OK

Page 10: Lec 4

BITS Pilani, Pilani Campus

Example 2

class 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:\java\bin>java test105HelloI am fine It is OK It is OK Again

Page 11: Lec 4

BITS Pilani, Pilani Campus

DEFINING A CLASS

SYNTAX

<scope> [<final>/<abstract>] [static>] class <classname>

[extends <classname>] [implements <interfacename 1> …….<interface n>]

{

Member Variable declarations /Instance field declarations;

Member Method Definitions;

}

Class Body

<scope> : 1. package private or public for outer classes2. private , public , protected, package private for inner classes

<final> : class definition is final and can not be extended by sub classes. final class can not have sub classes

<static> : static keyword can only be applied for inner classes. Outer classes can not be static.

<abstract> : abstract keyword specifies that class is abstract.

Page 12: Lec 4

BITS Pilani, Pilani Campus

Instance Variable Declaration Syntax <scope> [<final>] [<static>] <type> variable name = [value];

where

<scope> can be private, public, protected or by default friendly

<type > can be any primitive type or class type or interface type;

Method Declaration Syntax<scope> [<final>][<static> ][<synchronized>] [abstract]

<return type> methodname( argument list ) [throws exceptiontype1..exceptiontype n]

{

….. Method Body……

}

Where

<scope> can be private, public, protected or by default friendly<return type > can be any primitive type or class type or interface type;

Note :

Default Access is always friendly. i.e. inside the package

Page 13: Lec 4

BITS Pilani, Pilani Campus

Visibility of fields

Access Modifiers

Access Location

public protected Friendly

[package private]

private

Same Class Yes Yes Yes Yes

sub classes in same package

Yes Yes Yes No

Other Classes inSame package

Yes Yes Yes No

Subclasses in other packages

Yes Yes No No

Non-subclasses in other packages

Yes No No No

Page 14: Lec 4

BITS Pilani, Pilani Campus

Class Examples

1.

class xyz

{ …….. } // class is defined with friendly access

2.

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.

Page 15: Lec 4

BITS Pilani, Pilani Campus

Class Examples

4.

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

}

Page 16: Lec 4

BITS Pilani, Pilani Campus

Exercise 1

Define a class which encapsulates a point in 2 – dimensional space. It has following members X & Y coordinate values.

It supports following operations(i) Individual operation for setting the values for X and

Y coordinates(ii) Computing the distance between two points(iii) Checking two points for equality [ Two points are

equal if they have same values for X and Y coordinates]

(iv) Method for translating the values for X and Y

Page 17: Lec 4

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

Page 18: Lec 4

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

Page 19: Lec 4

BITS Pilani, Pilani Campus

How to Create an Instance of a class

(Creating Objects)

Objects are always created/constructed/instantiated dynamically using new opeartor.

Syntax :<ClassName> <object reference> = new ConstructorMethod(<parameters>);

Constructor Method Method having same name as name of class

Examples :

BOX b1 = new BOX(); // Valid iff constructor is unparametrized

BOX b2 = new BOX(10,6,8); // Valid iff constructor is parametrized

Page 20: Lec 4

BITS Pilani, Pilani Campus

Object Creation Examples

BOX b1 = new BOX();

BOX b2 = b1;

b2

b2 is just another reference for the same object

b1

BOXl b h

ONLY ONE OBJECT IS CREATED IN ABOVE STATEMENTS

Page 21: Lec 4

BITS Pilani, Pilani Campus

How to Access Class members1. Private members of a class are only visible inside class body.2. Protected members have package scope and are accessible to

subclasses in other packages as well.3. private protected members are only accessible to subclasses in same

package 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 through

objects of that class. (Except static fields which are accessible through class name)

Syntax. <object_reference>.<member_field> ; <object_reference>.<methodname(parameter_list)>;

Page 22: Lec 4

BITS Pilani, Pilani Campus

class 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 class

class 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 Folder\Java>java RectangleTestLength is:10Width is:8Area =80Length is:100Width is:80Area =0*/

Example

Page 23: Lec 4

BITS Pilani, Pilani Campus

class 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 Folder\Java>java RectangleTestLength is:0Width is:0Area =80Length is:0Width is:0Area =0*/

Page 24: Lec 4

BITS Pilani, Pilani Campus

Constructors

1. If a class has any method with the same name as its class then it is constructor method for that class

2. Used to initialize the objects upon creation

3. In the absence of constructor method we have to specifically add a method for object initialization

4. If no constructor is defined for the class then a default constructor is provided 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 for every object creation of that class.

Page 25: Lec 4

BITS Pilani, Pilani Campus

Types of Constructors

1. Unparametrized Constructor2. Parametrized Constructor3. Overloaded Constructor

Page 26: Lec 4

BITS Pilani, Pilani Campus

Unparametrized Constructor

• If a class does not supply any constructor then JRE supplies a default constructor with no parameters

• Class can have its own constructor of any types.

• If a class supplies its own constructor then default constructor becomes hidden.

Page 27: Lec 4

BITS Pilani, Pilani Campus

Class With No Constructor

class XYZ{double a,b;void setData(double x, double y){a = x;b = y;}void print(){System.out.println("a="+a);System.out.println("b="+b);}}

class XYZTEST{public static void main(String args[]){XYZ xyz = new XYZ();xyz.print();}}

D:\Java1>java XYZTESTa=0.0b=0.0

Page 28: Lec 4

BITS Pilani, Pilani Campus

Class With Constructor

class XYZ{double a,b;XYZ(){S.O.P(“Object XYZ created”);}}

class XYZTEST{public static void main(String args[]){XYZ xyz = new XYZ();}}

D:\Java1>java XYZTESTObject XYZ created

Class with Unparametrized Constructor

Page 29: Lec 4

BITS Pilani, Pilani Campus

class XYZ{double a,b;XYZ(double a, double b){this.a = a;this.b = b;print();}void print(){System.out.println("a="+a);System.out.println("b="+b);}}

class XYZTEST{public static void main(String args[]){// XYZ xyz = new XYZ(); WrongXYZ xyz = new XYZ(10.8,6.5);xyz.print();}}

D:\Java1>java XYZTESTa=10.8b=6.5a=10.8b=6.5

Class with Parametrized Constructor

Page 30: Lec 4

BITS Pilani, Pilani Campus

class XYZ{double a,b;XYZ(){a = 10;b = 8;print();} XYZ(double a, double b){this.a = a;this.b = b;print();}void print(){System.out.println("a="+a);System.out.println("b="+b);}}

class XYZTEST{public static void main(String args[]){XYZ x1 = new XYZ(); XYZ x2 = new XYZ(10.8,6.5);x1.print();x2.print();}}

D:\Java1>java XYZTESTa=10.0b=8.0a=10.8b=6.5a=10.0b=8.0a=10.8b=6.5

Class with Overloaded Constructor

Page 31: Lec 4

BITS Pilani, Pilani Campus

Constructor Examples(Parametrized Constructor)• class Triangle• {• double side1,side2,side3;• Triangle(double side1,double side2,double side3)• {• this.side1 = side1;• this.side2 = side2; • this.side3 = side3;• System.out.println ("Triangle Created with sides :"+side1 +" " +side2+ " "+side3);• }• }

class TriangleTest{public static void main(String args[]){// Triangle t1 = new Triangle(); This Line will give compile time error Triangle t1 = new Triangle(10.56,4.56,3.45); Triangle t2 = new Triangle(10,4,9); Triangle t3 = new Triangle(1,4,3);}}

Page 32: Lec 4

BITS Pilani, Pilani Campus

/* Out PutE:\New Folder\Java>javac TriangleTest.java

E:\New Folder\Java>java TriangleTestTriangle Created with sides :10.56 4.56 3.45Triangle Created with sides :10.0 4.0 9.0Triangle Created with sides :1.0 4.0 3.0*/

Page 33: Lec 4

BITS Pilani, Pilani Campus

Overloaded Constructors• class Triangle• {• double side1,side2,side3;• Triangle(double side)• {• side1= side2 = side3 = side;• System.out.println("Equilateral Triangle Created with sides :"+side);• }• Triangle(double side1,double side2)• {• this.side1 = side1; this.side2 = this.side3 = side2;• System.out.println("Isoceles Triangle Created with sides :"+side1 +" " +side2);• }• Triangle(double side1,double side2,double side3)• {• this.side1 = side1; this.side2 = side2; this.side3 = side3;• System.out.println("Triangle Created with sides :"+side1 +" " +side2+ " "+side3);• }• }

Page 34: Lec 4

BITS Pilani, Pilani Campus

class TriangleTest{public static void main(String args[]){ Triangle t1 = new Triangle(10.56,4.56,3.45); Triangle t2 = new Triangle(10,4); Triangle t3 = new Triangle(13);}}

/* OutputE:\New Folder\Java>java TriangleTestTriangle Created with sides :10.56 4.56 3.45Isoceles Triangle Created with sides :10.0 4.0Equilateral Triangle Created with sides :13.0*/