0% found this document useful (0 votes)
3 views50 pages

05 Classes and Objects

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views50 pages

05 Classes and Objects

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Classes and objects

OBJECT

 Previously we have studied OOP concepts.


 Object-oriented programming (OOP) involves programming using objects.
 An object represents an entity in the real world that can be distinctly
identified.
 For example, a student, a desk, a circle, a button, and even a loan can all
be viewed as objects.
 An object has a unique identity, state, and behaviors.
 The state of an object consists of a set of data fields (also known as
properties) with their current values.
 The behavior of an object is defined by a set of methods.
OBJECT

Class Name: Circle A Class template

Data Filed:
radius
Three object of
Method: The Circle class
getArea

Circle Object 1 Circle Object 2 Circle Object 3

Data Filed: Data Filed: Data Filed:


radius=10 radius=20 radius=30

An object has both a state and behavior. The state


defines the object, and the behavior defines what the
object does.
CLASS

 Classes are constructs that define objects of the same type.


 It is a template or blueprint from which objects are created. It is a
logical entity. It can't be physical.

 A Java class uses variables to define data fields and methods to


define behaviors.

 A class in Java can contain:


 Fields
 Methods
 Constructors
 Blocks
 Nested class
DEFINING CLASSES
 A class defines a new type.
 Once defined, this new type can be used to create objects of that type.
 The data and the operation on data is encapsulated in in a class. In
other words, a class is a template that contains the data variables and
the methods that operate on those data variables.
The general structure of a class is given below:

[modifiers] class <class_name> [extends classname] [implements interface1 [,


interface2]….]
{
<instance variables> Class Header
<class variables>
<constructors>
<methods definitions>
<initializer blocks>
} Class Body
DEFINING CLASSES
 Class header : it contains the following:
1. The name of the class preceded by the keyword class
2. Scope or accessibility modifier: public or private
3. Additional class modifiers: abstract, final etc.
4. The name of the class it extends
5. The names of interfaces it implements
 Class body: The class body contains all of the code that is provided for the life
cycle of the objects created from it.
1. Instance variables.
2. class variables
3. Constructors
4. Method declaration
5. Initialization block
6. Nested class and interface declaration
Note: The declaration can happen in any order
DEFINING CLASSES
public class Rectangle {
int length;
int breadth; Data Fields
public Rectangle() {
length = 1;
breadth = 1;
}
Constructors
public Rectangle(int l, int b) {
length = l;
breadth = b;
}
void setData(int x, int y) {
length = x;
breadth = y;
}
int getArea() {
return length * breadth; Methods
}
int getPerimeter() {
return 2*length+2*breadth;
}

}
TYPES OF CLASSES
 Concrete class:
A concrete class is a class which can be instantiated.
It is a complete class which defines data members, defines constructor,
define methods(member function) and can also be sub-classed.
 Abstract class:
An abstract class is an incomplete class which cannot be instantiated.
It often defines data members, defines constructors, defines some
methods, declares other methods(leaving definition to subclass(es))
 Interface or pure abstract class:
An interface is a pure abstract class. It simply declares methods and
can define constants as well
Defining methods
 A class encapsulates data members and methods.
 A method is a self-contained block of code that performs specific
operations on the data.

Return value Method Formal


Modifier
type name parameter
s
s
Method Actual
header
public static int max(int a,int b) parameter
s
{
int result = (a>b)?a:b;
Method
body Method int r = max(10,20);
return result; Signature
}
Return
value
• condition ? true : false

• a = 5;
(a < 4) ? “Hljsl” : “false” // Ternary Operator
{
int a;

}
DEFINING METHODS(CONT..)
 Name: The name is a valid java identifier which identifies the method and is also
used to call the method.
 Parameters: A method may have zero or more parameters defined in the
parentheses immediately following the method name during the method
declaration.
Parameters can be passed to methods in two ways: by value or by reference.
When a variable of primitive type is passed to a method, then it is passed by
value.
Other than primitive types all variables are passed by reference.
 Return type: If a method returns a value to the calling function, then the type of
the value which will be returned by function is the return type of function.
If function does not return value, then the return type of such a function is void.
Modifier can be one of the following:
1. access modifier: it could be public, private, protected or default
2. abstract: a function without definition, which subclass of the containing
class defines the body of function.
3. final: A final method cannot be overridden in a subclass.
4. static: A static method is a class method and invoked on behalf of an entire
DEFINING METHODS(CONT..)
 Method with variable number of parameters:
 Newer versions of java support methods which take a variable
number of parameters so that the same method may be invoked
with different number of parameters.
 These are also called variable-length argument methods.
The rules to define variable-length parameters in a method are:
(1)- There must be only one variable-length parameters list.
(2)- If there are individual parameters in addition to the list, the
variable-length parameters list must appear last.
(3)- The variable-length parameters list consists of a type followed
by three dots and the name of the parameter list.
 In the method, the parameters passed to the method as variable-length
parameter can be accessed as an array.
The name of variable-length parameters list is the name of array.
Defining methods(cont..)
Example:

public class VariableLengthArgument {


static void displayGreeting(String message, String... names) {
for (String one_name : names)
System.out.println(message + " " + one_name);
}
static int total(int... n) {
int sum = 0; Variable length
for (int i : n) argument
sum += i;
return sum;
}
Call with public static void main(String[] args) {
different displayGreeting("hello", "ahmad", "jawad", "qasem");
number of displayGreeting("hello", "ahmad", "jawad", "qasem", "ali", "jamal");
arguments System.out.println(total(10, 20, 50));
System.out.println(total(10, 20, 50, 80, 90, 60, 4, 5));

}
}
DEFINING METHODS(CONT..)
 Method overloading:
 In java, it is possible to create several methods that have the same
name, but different parameter lists and different definitions.
 This is called method overloading.
 Method overloading is commonly used to create several methods
with the same name that perform the same or similar tasks, but on
different types or different numbers of arguments.
 When we call a method in an object, java matches up the method name
first and then the number and type of parameters to decide which one
of the definitions to execute.
 The return type of the overloaded methods do not have effect on
overloading.
 Method overloading is one of the ways that Java supports
polymorphism.
DEFINING METHODS(CONT..)
public class MethodOverloading {
/* Return the max of two int values */
public static int max(int num1, int num2) {
return (num1 > num2) ? num1 : num2;
}
Same name
/* Find the max of two double values */
public static double max(double num1, double num2) {
return (num1 > num2) ? num1 : num2;
}

/* Return the max of three double values */


public static double max(double num1, double num2, double num3) {
return max(max(num1, num2), num3);
}

public static int square(int intValue) // square method with int argument
Same name
{
return intValue * intValue;
}

public static double square(double doubleValue)// square method with double argument
{
return doubleValue * doubleValue;
}
}
DEFINING METHODS(CONT..)
 Recursion:
Recursion is the process by which a function calls itself repeatedly, until
some specified condition has been satisfied.
Example: recursion function for finding the factorial of a number.

public class RecursionDemo {

static int factorial(int n) {


if(n<=1)
return 1;
else
return n*factorial(n-1);
}
public static void main(String[] args) {
System.out.println(factorial(7));
}
}
DEFINING METHODS(CONT..)
Example 2: recursion function for calculating xy.

public class Rectangle {

static int power(int x, int y) {


if (y == 0)
return 1;
else if (y == 1)
return x;
else
return x * power(x, y - 1);
}

public static void main(String[] args) {


System.out.println(factorial(7));
System.out.println(power(4,2));
}
}
CALLING METHODS
 Simply we can say that, calling a method executes the code in the
method.
 When a program calls a method, program control is transferred to the
called method.
 A called method returns control to the caller when its return statement
is executed or when its method ending closing brace is reached
BENEFITS OF METHODS
 Write a method once and reuse it anywhere.
 The max method can in previous example can be invoked/used
from/in any class.
 If you create a new class Test, you can invoke the max method using
ClassName.methodName (e.g., TestMax.max(5,10)).
 Reduce complexity.
 Information hiding. Hide the implementation from the user.
 You can think of the method body as a black box that contains the
detailed implementation for the method.
CONSTRUCTORS
 A constructors are a special methods of the class which have three
peculiarities:
1. Constructors must have the same name as class itself
2. Constructors do not have return type not even void
3. Constructors are invoked using the new operator when an object is created.
 Every time an object is created using new operator, at least one constructor is
called.
 At the time of constructor invocation, the memory is allocated to the object.
 Commonly, they are used for initializing the object’s data members.
 Similar to other methods, the constructors also can be overloaded.
 It makes it easy to create objects with different initial data values.
CONSTRUCTORS
 These special methods are called Constructors because they are used
to construct objects.
 To construct an object from a class, invoke a constructor of the class
using the new operator, as follows:
new Rectangle();//create object of Rectangle class
 Default constructor:
 This is a constructor with no parameters.
 If you do not define a constructor for a class, a public constructor
with empty body is automatically created by compiler.
 However, if you define any constructor for your class, a default
constructor is not longer automatically created.
CONSTRUCTORS

public class Rectangle {


// data fields
int length;
int breath;

// Default or no-argument constructor


Rectangle(){
length =0;
breath =0; Default constructor
}

public static void main(String[] args) {


Rectangle r = new Rectangle();//object creation,

}
}
New operator invokes the
constructor
CONSTRUCTORS
 Parameterized Constructors:
 Java supports method overloading. This means that two or more methods
can have the same signature within the same scope.

 We can add more constructors to the class with different signatures


 The job of the parameterized constructor is to assign specific values to data
member.

 Once we define a parameterized constructor, there is no need for defining a


method for setting the values of data members.

 Example:
new Rectangle(12);// passing a parameter to constructor
CONSTRUCTORS
public class Rectangle {
// data fields
int length;
int breath;

// Default or no-argument constructor


Rectangle(){
length =0;
breath =0;
}

//Parameterized constructor
Rectangle(int l,int b){
length = l;
breath = b;
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle();//invoke default constructor
Rectangle r2 =new Rectangle(5,9); //invoke parametrized constructor

}
}
THE SCOPE OF VARIABLES
 The scope of a variable is the part of the program where the variable
can be referenced or accessed.
 A variable defined inside a method is referred to as a local variable.
 The scope of a local variable starts from its declaration and continues
to the end of the block that contains the variable.
 A local variable must be declared and assigned a value before it can be
used.
 A parameter is actually a local variable. The scope of a method
parameter covers the entire method.
 You can declare a local variable with the same name multiple times in
different non-nesting blocks in a method, but you cannot declare a local
variable twice in nested blocks.
THE SCOPE OF VARIABLES
 A variable declared in the initial action part of a for loop header has its
scope in the entire loop.
 But a variable declared inside a for loop body has its scope limited in
the loop body from its declaration and to the end of the block that
contains the variable
THE SCOPE OF VARIABLES
CREATING OBJECT
 A class defines a new user defined type. This new type can be used to
create objects.
To create objects of a class, two steps must be followed:
1. Declare a variable of the class type. This variable does not create an object.
Instead, it is
simply a reference to an object
Syntax:
Class-name objectName;

2. Acquire an actual, physical copy of the object and assign it to that variable using
new
operator. The new operator dynamically allocate memory for object and
return a
reference to it
Syntax:
objectName= new ClassName();

 we can combine the above two steps in a single step.


ClassName objectName= new ClasssName();
Creating object
 Example :

MyRectangle r1;
r1= new MyRectangle();
MyRectangle

r1 r1
length
null

breadth
ACCESSING OBJECTS
 Referencing the object’s data:
objectRefVar.data
e.g.
myCircle.radius

 Invoking (calling) the object’s method (functions):


objectRefVar.methodName(arguments)
e.g.
myCircle.getArea()
REFERENCE DATA FIELDS
 The data fields can be of reference types. For example, the following
Student class contains a data field course of the Course type.

public class Student {

Course course; // course has default value null

int age; // age has default value 0

boolean isScienceMajor; // isScienceMajor has default value false

char gender; // c has default value '\u0000'

}
THE NULL VALUE
 If a data field of a reference type does not reference any object, the data
field holds a special literal value, null.
 Differences between Variables of Primitive Data Types and Object
Types

C r eated u si n g n ew C i r cl e( )

P r i m i ti v e ty p e int i = 1 i 1

O b j ect ty p e C i r cl e c c r efer en ce c: C i r cl e

r ad i u s = 1
COPYING VARIABLES OF PRIMITIVE DATA
TYPES AND OBJECT TYPES

P r i m i ti v e ty p e assi g n m en t i = j

B ef o r e: A f ter :

i 1 i 2

j 2 j 2
GARBAGE COLLECTION
 As shown in the previous figure, after the assignment statement c1 = c2,
c1 points to the same object referenced by c2.
 The object previously referenced by c1 is no longer referenced. This
object is known as garbage.
 Garbage is automatically collected by JVM.
 TIP: If you know that an object is no longer needed, you can explicitly
assign null to a reference variable for the object.
 The JVM will automatically collect the space if the object is not
referenced by any variable.
Static fields, method and blocks
Static methods:
Static methods are methods which are declared static. Static methods do not
belong to an object, but belong to the class.
They exists even when there are no objects. We have seen that main is a static
method.
A static method can be invoked using the class name without any object of class.
Syntax: ClassName.MethodName(args);
Rules for static variables and methods: The following rules apply to instance and
class members.
(1)- Instance methods can access instance variables and instance methods
directly.
(2)- Instance methods can access class variables and class methods directly.
(3)- Class methods can access class variables and class methods directly.
(4)- Class methods can not access instance variables and instance methods
directly, they must use an object reference to access the instance variables and
methods.
(5)- Class methods cannot use the this keyword as there is no object.
Static fields, method and blocks
Static fields, method and blocks
Static blocks:
In addition to static fields and methods, a class can have a static block which belongs to
the class.
This block will be executed even before main is invoked. This block is executed only once
when the class is loaded.
It’s main purpose is to initialize static variables.
Example:
class Example{
static int a;
static int b;
static{ // the static block
System.out.println(“static block is called”);
a=10; b=20;
}
static void Method(){
System.out.println(“a=“+a);
System.out.println(“b=“+b);
}
public static void main(String[] args)
{
method();
}
}
Static fields, method and blocks
Static fields:
When a number of objects are created from the same class, they each have their own
distinct copies of instance variable.
Sometime the variables which are common to all objects i.e. they do not belong to
each but belong to the class. This is accomplished using the static modifier. These
fields are called static fields or class variables. Every object shares a class variable,
which is at one fixe location in memory.
For example: we want to keep track of number of objects of class which are created.
class Myrect{
int a,b;
static int count=0;
public Myrect(int a,int b){
this.a=a; this.b=b; count++; }
}
Public class Testing{
public static void main(String[] args){
Myrect mr1= new Myrect(10,20);
Myrect mr1= new Myrect(40,50);
Myrect mr1= new Myrect(1,60);
System.out.println(Myrect.count);
}
}
// the out put will be 3
Initializing instance members
Non Static blocks:
Normally, we put code to initialize an instance variable in a constructor.
Another method to initialize an instance variable is by using an initialization block .
Initialization block for instance variables are a set of statements enclosed in {}
The compiler copies the initialization block in every constructor automatically. Hence, this
method is useful when the same code needs to be used in each constructor.
The following code illustrate this concept.
Class Employee{
int id;
String name;
static int nextId=1;
{ //initialization block
id= nextId;
nextId++;
name=“undefined”;
}
Array of objects
 In many case we need to create several objects. In such a case, we can
create an array of objects.
To create an array of objects, two steps should be followed:
1. Create an array of references using new
Syntax:
ClassName[] arrayName= new ClassName[size];
2. Create an object for each reference using new
Syntax:
for(int i=0; i<size; i++)
{
arrayName[i]=new ClassName();
this keyword
 The object which invoke a method is called the implicit or hidden object.
Sometimes a method may need to refer to this implicit object.
To allow this, java defines the this keyword. The this keyword always
refers to the current or implicit object.
Uses of this:
1. To resolve ambiguity between a local and instance variable.
2. To return the implicit object.
3. To invoke methods and access instance data members.
4. To invoke one constructor within another.
this keyword
Example:
class A
{
int a;
A()
{
this(0); // invoke constructor
}
A(int a)
{
this.a=a; // resolve name conflict
}
A modify()
{
this.a=400; // access instance data member
return this; // return implicit object
}
}
Package
 Package is an important and innovative concept in java. It is a naming
and visibility control mechanism.
 A package is a namespace that organizes a set of related classes and
interfaces. A package allows classes and interfaces to be grouped
together into a collection called “package”.
 Packages are basically containers for classes to keep the class
namespace compartmentalized.
 Conceptually you can think of packages as being similar to different
folders on your computer.
 Because software written in the java programming language can be
composed of hundreds or thousands of individual classes, it makes
sense to keep things organized by placing related classes and
interfaces into packages.
Package(cont..)
Predefined packages:
The standard java library contains several classes and interfaces which
are distributed over a number of packages.
To use these classes, you should import the package. The package which
is imported by default is the java.lang package which contains language
related classes. Some of the important predefined packages are:

Package Purpose
java.lang Language related(default package)
java.io Input-output classes
java.net Networking and web related
java.util Utility like Date etc.
java.awt AWT library(GUI) for designing user
interfaces
javax.swing Swing library(GUI)
java.awt.event Event handling
Creating Package
To create a user defined package, the package statement should be
written in the source code file.
This statement should be written as the first command in the file. Only one
package statement can be written in a file.
Syntax:
package <top_pkg_name>[.<sub_pkg_name>];
Example:
package mypackage; // a packaged named mypackage
package maths.algebra;// algebra is a package within maths package

Any class declared within that file will belong to that package.
All class files belonging to a package are stored in a directory(folder)
having same name as that of the package.
The directory(folder) should be created by user because it is not created
by default.
Creating Package
It is possible to have a subdirectories within a directory, so it is also
possible to have a package within another package. For example, we can
have a package algebra, within a package called maths.
The files related to the package “algebra” will be stored in a sub-directory
called algebra in the directory “maths”.
Accessing Package
To use classes of a package in another package, the class name must be qualified using
the package name.
Syntax:
packageName.ClassName
Example:
java.util.Scanner ip; //where ip is an reference of type Scanner class.
However, this is a cumbersome and difficult syntax. Every time the class needs to be
accessed, we have to use the package name as well.
An easier method is to use the import statement. It allows us to access a specific class
or all classes from a package. To import one class or all classes from a package, we use
the import statement.
Example:
import java.util.List; //imports List class
import java.io.*; // imports all classes from io package
Static import
A static import declaration enables you to import the static members of a class or
interface so you can access them via their unqualified names in your class—the class
name and a dot (.) are not required to use an imported static member.
A static import declaration has two forms—one that imports a particular static member
(which is known as single static import) and one that imports all static members of a
class (known as static import on demand).
The following syntax imports a particular static member:
import static packageName.ClassName.StaticMemberName;
where packageName is the package of the class (e.g., java.lang), ClassName is the name
of
the class (e.g., Math) and staticMemberName is the name of the static field or method
(e.g., PI or abs).
The following syntax imports all static members of a class:
import static packageName.ClassName.*;
Controlling access
Package provide a mechanism to control access to your class or interface.
Even at the class level, you may want to control access to an individual
member or method. Java provides access level modifiers to decide
whether other classes can use a specific field or invoke a method.
There are two level of access control:
1. At the class level:
A class may be declared as public or without any modifier. If it is
declared public, it is accessible to all classes everywhere. If it is not
declared with any modifier, the default access is package i.e. it is
accessible only within its own package.
2. At the member level:
A member(variable or method) may be declared as public, private,
protected or without any modifier. The following table shows the
effects of these modifiers.
Controlling access(cont..)

The following table shows the access rules for class members
Accessible to public protected none private
Same class Yes Yes Yes Yes
Class in the same package Yes Yes Yes No
Subclass in any package Yes Yes No No
Non subclass in other Yes No No No
package

You might also like