05 Classes and Objects
05 Classes and Objects
OBJECT
Data Filed:
radius
Three object of
Method: The Circle class
getArea
}
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.
• 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:
}
}
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;
}
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.
}
}
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.
Example:
new Rectangle(12);// passing a parameter to constructor
CONSTRUCTORS
public class Rectangle {
// data fields
int length;
int breath;
//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();
MyRectangle r1;
r1= new MyRectangle();
MyRectangle
r1 r1
length
null
breadth
ACCESSING OBJECTS
Referencing the object’s data:
objectRefVar.data
e.g.
myCircle.radius
}
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