You are on page 1of 60

Object Oriented Programming

Techniques

Lecture 6: Classes &Object

Prepared By : Umm-e-Laila 1
Classes And Objects
A class is a programmer defined type that serves as a blue print for instances
of class.
e.g. you can have int ,float etc but can also have like motorcycle, tube light
etc
Class define behavior and data. A class has two parts
Field i.e. data specify what the class is and whatsa its properties are.
Behavior i.e. method specify what the class does.

Fields

behavior

Defining Classes:
A class definition specify a new TYPE and its implementation.
General Syntax :
<class header>{
<class body>}
in class header , the name of the class is preceded by the keyword
class. In addition the class header can specify the following
information
 Scope or accessibility modifier

 Additional class modifiers

 Any class it extends

 Any interface it implements.

Class body contain variables and method called members.


Members belonging to the class are called static members.
Members belonging to the objects of the class are called instance members.
Class body can contain decelerations of other classes and interface as
members.(nested classes)
Class body can contain static and instance initializers.
Variable defined within a class are called instance variable because each instanc
of the class ( object of a class) contains its own copy of these variables.
Note: Objects send message to each other by calling methods.
Instance method belong to particular objects.
Static methods belong to a particular class.
 Example :Class
 class Car{
 String licensePlate; // “Karachi 543 A23”
 double speed; //in km per hour
 double maxSpeed; //in km per hour
 }
 variable licensePlate, maxSpeed, speed are
called member variables, instance variable or
fields of the class
 Defining Methods:
 The behavior of objects is specified by the methods of
the class. Like member variable member methods can
be characterized as
 Instance methods
 Static methods
 Syntax is:
 <method header>(<formal _parameters _list)<throws
clause>{
 <methods body>
 }
 method header specify :
 Scope or accessibility modifier
 Additional method modifiers
 Return type of the method
 Method:
 Instance method
 Must be called by a instance of a class..
 Class method (static)
 Class method can be executed when no object of a class exist .
static method can’t be refer by a instance or object of a class.(give
compile error)
 Instance Methods
 Non-static methods are also called instance methods.
 An instance method is called for a particular object using “dot
notation”:
 objName.instMethod(...);
 Instance methods can access ALL fields and call ALL methods of
their class — both class and instance fields and methods.
Static (Class) vs. Non-Static
public class MyClass
{
(Instance)
public static final int statConst; 
private static int statVar; public int instMethod(...)
{
private int instVar; statVar = statConst;
... inst Var = statConst;
All OK instVar = statMethod(...);
...
statVar = instMethod2(...);
public static int statMethod(...) ...
{ }
statVar = statConst;
statMethod2(...); public int instMethod2(...)
OK {
instVar = ...; ...
instMethod(...); Error! }
} Continued ...
 }
Note: main is static and therefore cannot access non-static fields or call
non-static methods of its class:

public class Hello


{ Error:
private String message = "Hello, World"; non-static
variable
public static void main (String[ ] args)
{
message is
System.out.println (message); used in static
} context (main)
}
Static Methods
 Static methods can access and manipulate a class’s static fields.
 Static methods cannot access non-static fields or call non-static
methods of the class.
 Static methods are called using “dot notation”:
ClassName.statMethod(...)
 double x = Math.random();
 double y = Math.sqrt (x);
 System.exit();
Setter Method:
 Also known as mutator A programmer often provides methods,
called accessors, that return values of private fields; methods that
set values of private fields are called modifiers
 Example

class Car{
String licensePlate; // “Karachi 543 A23”
double speed; //in km per hour
double maxSpeed; //in km per hour
public void SetmaxSpeed(double maxSpeed){
If(maxSpeed>0.0)
this.maxSpeed=maxSpeed;
else maxSpeed=0.0;
}

}
 Getter Method:
 Also known as Accessor methods use to get the values
of a field .
Example
class Car{
String licensePlate; // “Karachi 543 A23”
double speed; //in km per hour
double maxSpeed; //in km per hour
public double GetmaxSpeed(){ return this.maxSpeed;
}

}
 return
 A method, unless void, returns a value of the specified type to the
calling method.

return expression;
The type of the return
value or expression must
match the method’s
declared return type.

 The return statement is used to immediately quit the method and


return a value:
 So a return statement does two things: quits the method and
returns a value to the calling method.
 Defining Variable in class:
 Instance variable
 Each object created will have its own copy o f the
variable defined in the class.
 Class variable (static)
 Each object will shared a single copy of variable . Also
the variable is exists even if no object is created.
 They belong to a class can refer by the class and
object. If value of class variable is change all variable will
be effected by that change. Use a keyword static.
Overloaded Methods:
 One word, many meanings: overloaded
 Unique argument type combinations distinguish
 overloaded methods
public void move (int x, int y) { ... }
public void move (double x, double y) { ... }
public void move (Point p) { ... }
public Fraction add (int n) { ... }
public Fraction add (Fraction other) { ... }

 Methods of the same class that have the same name but different
numbers or types of arguments are called overloaded methods.
 Use overloaded methods when they perform similar tasks:
 The compiler treats overloaded methods as completely different
methods.
 The compiler knows which one to call based on the number and the
types of the arguments
 Overloading on Return Values
 Why not also use return values in
methodOverloading?
 void f() {...}
 int f() {...}
 Then what would this mean?
 f();
The this Reference
•Every instance method has a variable with the name this ,
which refers the current object for which the method is being called.
It is used implicitly by the compiler when your method refers to an
instance variable of the class.
Example
Return this.a * this.b;
•The this reference allows an object to refer to itself.
The this reference can also be used to distinguish the parameters
of a constructor from the corresponding instance variables with
the same names
public Account (Sring name, long acctNumber, double balanc
{
this.name = name;
this.acctNumber = acctNumber;
this.balance = balance;}
Objects:
Constructing objects with new:
To instantiate an object in java use new keyword followed by a call to the class
constructor.
e.g Car c=new Car();
or Car c; // declares a reference of Car type variable
c=new Cat();
•Constructor is a method that creates a new instance of a class.

•When an object is created its instance variable are declered to there default
values.
license Plate=null
speed=0
maxSpeed=0

Car c;

null
Object Variables are References
public class Student {
public char grade;}

public class PointerTest {


public static void main( String args[] ){
Student sam = new Student(); Grade=’A’
sam.grade = 'A';
Student samTwin =new Student(); Grade=’D’
samTwin.grade = 'D';
samTwin = sam;
samTwin.grade = 'C';
Grade=’C’
System.out.println( sam.grade ); sam
}}
Grade=’D’
Output
C Sam twin
Aliases

 Two or more references that refer to the same


object are called aliases of each other
 One object (and its data) can be accessed using
different reference variables
 Aliases can be useful, but should be managed
carefully
 Changing the object’s state (its variables)
through one reference changes it for all of its
aliases
The null Reference
•An object reference variable that does not currently point to an object is
called a null reference
•The reserved word null can be used to explicitly set a null reference:
name = null;
or to check to see if a reference is currently null:
•if (name == null)
System.out.println ("Invalid");
•An object reference variable declared at the class level (an instance variable)
is automatically initialized to null.
•The programmer must carefully ensure that an object reference variable
refers to a valid object before it is used
•Attempting to follow a null reference causes a NullPointerException to be
Thrown.
•Usually a compiler will check to see if a local variable is being used without
being initialized
Testing Objects for Equality:
 The == operator compares object references for
equality, returning true if the references are
aliases of each other
 C1 == ==C2
 A method called equals is defined for all objects,
but unless we redefine it when we write a class,
it has the same semantics as the == operator
 bishop1.equals(bishop2)
 We can redefine the equals method to return
true under whatever conditions we think are
appropriate
Constructors:
 A constructor is like a method for creating objects of the
class.
 A constructor often initializes an object’s fields.
 Constructors do not have a return type (not even void) and
they do not return a value.
 All constructors in a class have the same name — the name
of the class.
 Constructors may take arguments
 If a class has more than one constructor, they are
“overloaded” and must have different numbers and/or types
of arguments.
 Programmers often provide a “no-args” constructor that
takes no arguments.
 If a programmer does not define any constructors, Java
provides one default no-args constructor, which allocates
memory and sets fields to the default values
<accessibility modifier> <class name> (<formal parameter list )
  { // Constructor body
    <local variable declarations>
    <nested local class declarations>
    <statements> }
public class Fraction
{
private int num, denom;

public Fraction ( )
{
num = 0;
denom = 1;
}

public Fraction (int n)


{
num = n;
denom = 1;
} Continued 
•Constructors of a class can call each other using the keyword
this — a good way to avoid duplicating

public class Fraction ...


{ public Fraction (int p, int q)
... {
num = p;
public Fraction (int n) denom = q;
{ reduce ();
this (n, 1); }
} ...
...
Default Constructor
 Constructors are needed to create instances
(objects) of a class
 Compiler provides one for you if you write no
constructor
class Bird {
int i;}
public class DefaultConstructor {
public static void main(String args[]) {
Bird nc = new Bird(); // default!}}

 The implicit default constructor is equivalent to


the following implementation:
 <class name>() { super(); }
 class can choose to provide an implementation
of the default constructor. the class Light
provides an explicit default constructor.
 class Light {

Light() {
noOfWatts = 50;
indicator = true;
location = "X"; } }
 If a class defines any explicit constructors, it can
no longer rely on the implicit default constructor
to set the state of the objects
 If such a class requires a default constructor, its
implementation must be provided.
Constructor Overloading
 • Like methods constructors may be overloaded
 class Tree {
 int height;
 Tree() {
 System.out.println("A seedling");
 height = 0;
 }
 Tree(int i) {
 System.out.println("A new Tree, "
 + i + " feet tall");
 height = i; }
 }
COPY CONSTRUCTOR:
 If Sphere a=b;// b is also of type a therefore a and b
points to the same obj reference. But you will not have
distinct objects.
 For distinct objects use Copy constructor.
 Sphere(final Sphere OldSphere)
 {
 radius = OldSphere.radius; // Set the radius
 // Set the coordinates of the center
 xCenter = OldSphere. xCenter;
 yCenter = OldSphere .yCenter;
 zCenter = OldSphere. zCenter;
 }
Operator new

 Constructors are invoked using new


 Fraction f1 = new Fraction ( );
 Fraction f2 = new Fraction (5);
 Fraction f3 = new Fraction (4, 6);
 Fraction f4 = new Fraction (f3);
 You must create an object before you can use it;
the new operator is a way to do it
 Fraction f;
 f = new Fraction (2, 3);
 f = new Fraction (3, 4);
this in Constructors
 • A very common kind to use this is in
constructors to
 initialize data members with the constructor's
arguments
 public class Animal {
 private int numberOfLegs;
 Animal(int numberOfLegs) {
 this.numberOfLegs = numberOfLegs;
 }
 }
Passing Arguments to Constructors
and Methods
 Any expression that has an appropriate data type
can serve as an argument:
double a = 3, b = -4;
Polynomial p = new Polynomial(1.0, -(a + b), a * b);
double y = p.getValue ( 2 * b - a);
 int is promoted to double when necessary

 A “smaller” type can be promoted to a “larger” type

(e.g., int to long, float to double).


 Primitive data types are always passed “by value”:

the value is copied into the parameter


double x = 3.0; x: 3.0
double y = p.getValue ( x );

y:
public class Polynomial copy
{
... public double getValue (double u)
{
double v;
... u: 3.0
}
} u acts like a local
variable in v:
getValue
Objects as parameters
Fraction f1 = new Fraction (1, 2); f1: addr1
Fraction f2 = new Fraction (5, 17);
Fraction f3 = f1.add (f2);
f2: addr2

public class Fraction


copy
{
...
public Fraction add (Fraction f)
{
Fraction sum; f: addr2
...
} sum:
}
class Car{
String licensePlate; // “Karachi 543 A23”
double speed; //in km per hour
double maxSpeed; //in km per hour
public void Check(Car obj){
System.out.println(obj.speed);
Obj=null // only destroy photocopy of the reference
}

} public class CarChecking{


public static void main(String args[]){
Car c =new Car();
c.Check(c);
}}
 obj c reference is photocopied and send to
Check method . if any changes will be done it
will show if we delete the object it will delete the
photocopy of the reference.
 To eliminate changes use final keyword. In final
reference can’t be change only value is changed
therefore we can’t write obj=null;(gives compile
time error)
 public void Check( final Car obj){
 Final use with class, method and variable
Garbage Collection

 When an object no longer has any valid


references to it, it can no longer be accessed by
the program
 The object is useless, and therefore is called
garbage
 Java performs automatic garbage collection
periodically, returning an object's memory to the
system for future use
 In other languages, the programmer is
responsible for performing garbage collection
Initialization Blocks
 A initialization block is a block of code between braces that is
execued before an object of the class is created.
class TryInitialization
{
static int[] values = new int[10]; // Static array member
// Initialization block
{System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random()); }

// List values in the array for an object


void listValues()
{System.out.println(); // Start a new line
for(int i=0; i<values.length; i++)
System.out.print(" " + values[i]); // Display values
System.out.println(); // Start a new line
}
public static void main(String[] args)
{
TryInitialization example = new TryInitialization();
System.out.println("\nFirst object:");
example.listValues();
TryInitialization nextexample = new TryInitialization();
System.out.println("\nSecond object:");
nextexample.listValues();
example.listValues();
}
}
output:
First object:
97 40 26 23 71 36 13 92 32 7
Running initialization block.
Second object:
87 71 19 0 40 85 17 24 85 97
87 71 19 0 40 85 17 24 85 97 // array is static
 Static Initialization Blocks

A static initialization block is an initialization block
preceded with the quantifier "static".
 A static initialization block is normally executed only once
each time your program is run.
 It will be executed before any object is created or any
reference is to the class is actually made in your
program.
 If more than one static block exists in the class, then
they are executed in order, from top to bottom of the
class.
 The static block can only reference static methods and
static fields.
 Any static field referenced in the static block must be
declared before the static block.
 This restriction does not hold for static methods
class TryInitialization
{ static int[] values = new int[10]; // Static array
member // //Initialization block
Static {
System.out.println("Running initialization block.");
for(int i=0; i<values.length; i++)
values[i] = (int)(100.0*Math.random());}
void listValues()
{ System.out.println(); // Start a new line
for(int i=0; i<values.length; i++)
System.out.print(" " + values[i]); // Display
values
System.out.println(); // Start a new line
}
public static void main(String[] args) {
TryInitialization example = new
TryInitialization();
System.out.println("\nFirst object:");
example.listValues();
TryInitialization nextexample = new
TryInitialization();
System.out.println("\nSecond object:");
nextexample.listValues();
example.listValues(); }}
output:
First object :40 97 88 63 56 46 84 6 32 69
Second object :40 97 88 63 56 46 84 6 32 69
Constant Fields
Declaring a field final means that it can only be set once
public class Constants
{
protected final int SIZE = 10;
protected final int[] CLASS_ARRAY = new int [ SIZE ];
protected final int NO_VALUE_YET; // blank final
public void aMethod( int input, final float FIXED)
{
final int NEW_FEATURE = 123;
final int ALSO_FIXED = input;
CLASS_ARRAY[ 3 ] = input;
}
public Constants( int aValue )
{
NO_VALUE_YET = aValue;
}

public static void main( String args[] )


{
Constants test = new Constants( 5);
test.aMethod( 13, 2.2f);
System.out.println( test.NO_VALUE_YET ); // Prints 5
}
}
Blank Final Rules
 A blank final is a final variable declaration that lacks an
initializer
 A blank final must be assigned exactly once

A blank final class (static) variable must be assigned by
one static initialization block
 blank final class variable can not be assigned in more
than one static initialization block

A blank final instance variable be assigned by one non-
static initialization block or else by every constructor in
the class
Blank Final Rules - Examples

public class StaticConstants


{
protected static final int SIZE;
static
{
SIZE = 123;
}
}
public class Constants
{
protected final int SIZE;
{
SIZE = 123;
}
}
Access Levels for Fields and
Methods
 public
 Members declared public are accessible anywhere the class is
accessible
 protected
 Members declared protected are directly accessible to any
subclasses, and directly accessible by code in the same package
 private
 Members declared private are accessible only in the class itself
 Friendly/package level
 A member is declared package level access by not explicitly
declaring the member any access level
 Members with package access are directly accessible only to code
in the same package
 Subclasses in different packages can not directly access the
member directly
 Example:
public class AccessLevels {
public int publicObjectVariable ;

protected float protectedObjectVariable = 10;


private int[] privateObjectVariable;
int packageAcceess = publicObjectVariable;
public AccessLevels ( int startValue )
{ System.out.println( " Start Constructor" );
privateObjectVariable = new int[ startValue ]; }

public void sampleMethod( int value )


{ System.out.println( " In method" );
privateObjectVariable[ 1 ] = value; }}
public class TestAccessLevels
{ public static void main( String args[] )
{ AccessLevels test = new AccessLevels ( 11 );
test.publicObjectVariable = 100; // Ok
test.protectedObjectVariable= 100; // Ok
test.privateObjectVariable[ 1 ] = 100; // Compile Error
test.packageAcceess = 100; // Ok }}
 Class Access Levels
 Public
 Accessible to code in and outside a package
 Package/friedly
 Accessible to code in package only
 No subclasses outside package allowed
 Used as helper classes in package
 package Botany;
 public class Leaf
 {

 public Leaf()
 {
 System.out.println( "Leaf in a real tree" );
 }
 }
 package Botany;
 class BotanyHelper
 {
 // Only code in package Botany can use this class
 }
 Recursion:

Method that call itself is called resursive method.
public class PowerCalc
{
public static void main(String[] args)
{ double x = 5.0;
System.out.println(x + " to the power 4 is " + power(x,4));
System.out.println("7.5 to the power 5 is " + power(7.5,5));
System.out.println("7.5 to the power 0 is " + power(7.5,0));
System.out.println("10 to the power -2 is " + power(10,-2)); }
static double power(double x, int n)
{ if(n > 1)
return x*power(x, n-1); // Recursive call
else if(n < 0)
return 1.0/power(x, -n); // Negative power of x
else
return n == 0 ? 1.0 : x; // When n is 0 return 1, otherwise x }}
output:
G:\java\prog>java PowerCalc
5.0 to the power 4 is 625.0 7.5 to the power 5 is
23730.46875
7.5 to the power 0 is 1.0 10 to the power -2 is 0.01
Package concept
• A Package is a logical grouping of classes
– Primarily to a void name clashes
– Identifies where the class code can be found
com.qatraining.cad.vehicle
Engine Truck

Car Gearbox

• Packages are organised hierarchically


– Maps to a hierarchical directory structure
– May map to an Internet domain Car.class
Engine.class
com vehicle
cad Truck.class
qatraining
Gearbox.class
 Referring to classes in a package

The name of a class includes its package, and can be quite long
edu.purdue.tech.vehicle.Car car1; -
vehicle.Car car1;
Car car1;

 Import Statement

The import statement allows you to use short class names


Both the examples below will compile and run
import statements enable abbreviated names to be used
Import must be placed before the first class description
If a class is in two imported packages, their full names must be used to
disambiguate them
The package java.lang is imported implicitly, therefore any of its
classes can be used without qualification
 Two use the two Leaf classes below in the same code
we can:
 Use the full name of each class
 Import one class and use the full name of the other class
 Import both packages on demand to import other classes
in each package and use the full name for the Leaf
classes
 File SearchTree/Leaf
package SearchTree;
public class Leaf
{
public Leaf()
{System.out.println( "Leaf in a binary search tree" );}}
 File Botany/Leaf
package Botany;
public class Leaf
{ public Leaf()
{ System.out.println( "Leaf in a real tree" );}}
 Use Full Names
class Test
{ public static void main( String args[] )
{ Botany.Leaf green = new Botany.Leaf();
SearchTree.Leaf node = new SearchTree.Leaf(); }}
 Import One Leaf
import SearchTree.Leaf;
class Test
{ public static void main( String args[] )
{ Botany.Leaf green = new Botany.Leaf();
Leaf node = new Leaf(); }}
Importing Both Leaf Classes - Error
import SearchTree.Leaf;
import Botany.Leaf; // Compile error
class Test
{ public static void main( String args[] )
{ Botany.Leaf green = new Botany.Leaf();
Leaf node = new Leaf();}}
 What should this do? And Why?
import SearchTree.Leaf;
import Botany.*;
class Test
{public static void main( String args[] )
{ Botany.Leaf green = new Botany.Leaf();
Leaf node = new Leaf();}}
 Import on Demand
 You can replace the class name in the import
statement with an "*".
 This will import all classes in that package
and is called import on demand
 The following import statement will import all
classes in the EDU.sdsu.roger package
 import EDU.sdsu.roger.*;
FINALIZE
 Automatic memory reclaim in java i.e garbage
collector.
 When object is create a low priority is give by the
JRE. That check that if it is null. The GC take its
but no time is give to destroy the object by the
GC.we use finalize method in which we can
write code which execute when object is destroy.
 System.gc or Runfinalize() explicitly enforce GC
to Run Finalize method
Protected void finalized(){
//Execute code when object is destroyed. When
object is destroyed finalized must execute.
}
class Point
{ double x;
double y;
Point(double xVal, double yVal)
{x = xVal;
y = yVal; }
public void finalize() // CANT BE PRIVATE AND
FRIENDLY
{System.out.println("Points obj is destroyed");}
}
public class TryPoint
{
public static void main(String[] args)
{Point start = new Point(0.0, 1.0);
start=null;
System.gc();}}
 Object's Methods (minus thread related)

clone() Creates a clone of the object.

 equals(Object) Compares two Objects for equality.


Uses "==" to test for equality

 finalize() Code to perform when this object is garbage collected.

 getClass() Returns the Class of this Object.

 hashCode() Returns a hashcode for this Object.

 toString() Returns a String that represents the value of this Object.

If a class needs an implementation of equals, which differs from the default


"equals", the class should override both equals and hashCode
If two different objects satisfy the equals method, the hashCode should return
the same value for both objects
 Initialization Order

A class is initialized when it is first "actively" used, i.e.


 A method defined in the class is invoked
 A constructor in the class is invoked
 A non-constant field in the class is accessed
 A class is initialized by performing direct assignments of
static fields and static initialization blocks are done in order
from top to bottom of the class
 When an object is created, after the class in initialized, all
instance field are initialized by: performing direct
assignments of non-static fields and instance initialization
blocks are done in order from top to bottom of the class,
then the constructor is executed
 Initialization Order and Forward References
 Don't Mix
 When you initialize a field you can not make a forward
reference another field
 public class ForwardReferenceAndInitialization
 { public static int first = 1;
 public static int second = first * 2;
 public static int third = fourth - 1; // Compiler error
 public static int fourth = 4;
 public int fifth = 5;
 public int sixth = fifth + 1;
 public int seventh = eighth - 1; // Compiler error
 public int eighth = 8;}

You might also like