Sei sulla pagina 1di 50

Day2

Java Essentials

Primitive Data Types in Java


Java Programming language is strongly typed
All variables must be first declared before they can be used

Byte: 8 bit signed integer. Values minimum (-128) to max 127(inclusive) Short: 16 bit signed integer. Values min(-32,768) to 32767(inclusive) Int: 32 bit signed integer. Values minimum(2,147,483,648 ) to (2,147,483,647 ) Long:64 bit signed integer Float: 32 bit(3.4e-038 to 3.4e+038) Double:64 bit Char:16 bit Unicode character Boolean can only take true or false
2

Scope
Local Scope: Variable will not be available outside its scope public static void main(String args[]) { int x; if(x==10) { int y = 20; System.out.println(x is + x +y is + y); } System.out.println(y is +y); //error }
3

Scope Error
public static void main(String args[]){ int bar =1; { int bar =2; } }

Type Casting
Automatic Type Conversions
Two types are compatible Destination type is larger than source type This type of conversion is called widening conversion

Casting Incompatible Types int a; byte b; b = (byte) a;

Type Casting
Truncation Conversion int i; double d = 1.23; i = (integer)d; Automatic Type Promotion byte b = 50; b = b*2;

Classes and objects


A class creates a new data type that can be used to create objects. Act as a blueprint A class is a logical construct Object is nothing but an instance of the class An object has physical reality i.e. it occupies space in memory

Declaring Objects
Class-var = new classname(); Classname followed by parentheses specifies the constructor for the class A constructor defines what occurs when an object of a class is created

Introducing methods
Although it is perfectly fine to create a class that only contains data, rarely happens Most of the time methods to access the instance variables defined by class What if another part of the program want volume? Type name (parameter-list){ body of method } Type specifies the type of data returned. Can be any valid type. return value;
10

11

Method that takes parameter


Adding a Method That Takes Parameters int square(){ Return 10*10 } Int square(int i){ return i*I; } Int x = square(5);
12

Method that takes parameter


Parameter is a variable defined by a method that receives a value when method is called An argument is a value that is passed to a method when it is invoked

13

Method that takes parameter


Can use a parameterized method to improve Box class In previous example mybox1.width=10; etc Code is clumsy and error prone Never a good idea to access variables directly Void setDim(double w, double h, double d){ Width = w; height = h; depth = d; mybox1.setDim(10, 20, 5); Vol=mybox1.volume();

14

Constructors
It can be tedious to initialize all of the variables in a class each time an instance is created Even setDim is not right A constructor initializes an object immediately upon creation It has the same name as the class in which it resides and is syntactically similar to method Once defined, constructor is automatically called immediately after the object is created, before new operator completes
15

Constructors
Constructors do not have any return type, not even void Implicit return type of a class constructor is the class type itself Creating an instance will have fully initialized usable object immediately Rework Box example so that dimensions are automatically initialized Replace setDim with a constructor
16

Constructors
Box2(){ System.out.println("Constructing Box"); width = 10; height = 10; depth = 10;}

17

Parameterized Constructors
In the previous example it is not very useful So add parameters to constructor Box(double w, double h, double d){ Width=w; height=h; }

18

The this keyword


Sometimes the method will need to refer to the object that invoked it To allow this java, java defines the this keyword this can be used inside any method to refer to the current object Is always a reference to the object on which method was invoked

19

Instance Variable Hiding


Illegal in java to declare to declare two local variables with same name inside the same or enclosing space Box(double width, double height, double depth){ this.width=width; this.height=height; this.depth=depth }
20

Overloading methods
In java it is possible to define two or more methods within the same class that share the same name as long as different parameter declaration This is called method overloading One of the ways java implements polymorphism

21

Overloading methods
One way java implements polymorphism i.e. one interface, multiple methods In languages that do not support method overloading, each method has unique name In C, abs() absolute value of integer labs() absolute value of a long integer fabs() absolute value of a floating point value In java standard, abs method is overloaded to handle all numeric types Left to the compiler to chose right version
22

Argument Passing
Call-by-value: Copies value of an argument into formal parameters. Therefore changes made to parameter of the subroutine have no effects on the argument used to call. Call-by-reference: A reference to argument, not value is passed. Changes made to parameter will change argument When a simple type is passed , it is done by use of call by value. Objects are passed by use of call-byreference
23

Inheritance
Very important component of object-oriented programming as allows hierarchical classifications Each class can use things that are unique to it Animal (Age, sex, weight) Mammal (Gestation period, etc) Canine (Hunting Skills, tail length) Dogs (trained, indoor/outdoor) Labrador

24

Inheritance
Enables you to create more specific classes Enables software reuse Parent class is called superclass Child class is called subclass

25

Inheritance Example
Class A { int i; int j; showij(){ System.out.println(I and j:+ i+ + j); } }

26

Inheritance Example
Class B extends A{ int k; void showk(); { System.out.println(k); } void sum(){ system.out.println(i+j+k); } }
27

Inheritance Example
Class SimpleInheritance{ Public static void main(String args[]} A superObj = new A(); B subObj = new B(); superObj.i = 10; superObj.j = 20; superObj.showij(); subObj.i = 7; subObj.i = 8; subObj.k = 9; subObj.showij(); subObj.showk();
28

Inheritance
We can use a super class directly Unlike C, Java does not support the inheritance of multiple classes into a single sub class Although a subclass includes all of the members of its super class, cannot access private members

29

Cannot Access Private Data


Class A { int i; private int j; setij(int x, int y){ i=x; j=y; } }

30

Error Accessing Private Data


Class B extends A { int total; void sum() { total = i+j } }

31

Super class variable can Refrence sub class variable


When a reference to a subclass object is assigned to a superclass reference variable, only access to those parts which are defined in superclass Boxweight weightbox = new Boxweight(3,5,7,9); Box plainbox = new Box(); . plainbox = weightbox;
32

Super class variable can Refrence sub class variable


{ Car x; Ford escort; x = escort;

// but cannot access ford specific features coz the parent class does not know about them

33

Using super
Classes derived from box were not implemented as efficiently and robustly. Duplicate in superclass, inefficient Also subclass must be granted access to these members But usually superclass keeps details of its implementations to itself i.e. encapsulation Java provides a solution to this with keyword super

34

Using super
A subclass can call a constructor method defined by its superclass by use of following form super(parameter-list); Parameter list specifies any parameters needed by the constructor in superclass Super() must always be the first statement inside subclass constructor

35

Using Super
Class BoxWeight extends Box{ double weight; BoxWeight(double w, double h, double d, double m); super(w,h,d); weight = m; }

36

Second use of super


super.member

37

Using Super
Class A{ int i; } Class B extends A{ int i; B(int a, int b){ super.i = a; i=b;} void show(){ System.out.println(I in superclass + super.i); System.out.println( I in subclass: + i); } Class useSuper{ public static void main(String args[]) B obj1 = new B(1, 2); obj1.show(); }
38

When Constructors are Called


Class A{ A() { System.out.println( inside As const); } Class B extends A{ B() { System.out.println( inside Bs const); } } Class C extends B{ C() { System.out.println( inside Cs const); } }
39

Class callConst { C obj = new C(); } Output Inside As Constructor Inside Bs Constructor Inside Cs Constructor

40

Method Overriding
When method in a subclass has same name and type signature as method in its superclass then method in subclass is said to override method in superclass

41

Dynamic Method Despatch


Class A{ callme() { System.out.println( inside As callme); } Class B extends A{ callme() { System.out.println( inside Bs call me); } } Class C extends B{ callme() { System.out.println( inside Cs callme); } }
42

Class Dispatch { public static void main(String args[]) A a = new A(); B b = new B(); C c = new C(); A r ; r = a; r.callme(); r = b; r.callme(); r =c; r.callme(); }
43

Abstract Classes
Super class that declares the structure of a given abstraction without providing complete implementation Super class that defines a generalized form and leave specific implementation to subclasses All methods which needs to be declared are declared as abstract Any class which contains abstract methods is defined as abstract class
44

Abstract Classes
abstract class A { abstract void callme(); void callmetoo() { System.out.println(This is a concrete method); } class B extends A{ B b = new B(); void callme() { System.out.println(Bs implementation of callme); } }
45

Using final
Keyword final has three uses Create equivalent of a named constant When used with method name, it prevents the method from being overriden When used with a class name it prevents the class from being inherited.

46

Passing Objects as Parameters


Both Common and right to pass objects to classes Already defined classes as well as custom classes can be sent as parameters

47

Argument Passing
Two Ways through which a computer Language can pass Arguments
Call-by-value Method Copies the value of an argument into formal parameters of subroutine Call-by-reference Reference to an argument (not values of the arguments) is passed to the parameter. Reference used to access actual arguments

48

The Object Class


Object Clone() boolean equals(Object obj) Void finalize() Class getClass() String toString() Void notify Void notifyAll Void wait()

49

Lab3

50

Potrebbero piacerti anche