You are on page 1of 26

CLASSES, OBJECTS and

METHODS [24]

Class
User-defined data type with a template that
serves to define its properties
A class is the blueprint of an object
The class uses methods to define the
behaviors of the object
The class that contains the main method of a
Java program represents the entire program
Multiple objects can be created from the
same class
Syntax:
class classname [extends superclass]
{
fields declaration;
methods declaration;
}

Objects
Is a block of memory that contains space to
store all instance variables
An object has:
state - descriptive characteristics
behaviors - what it can do

The state of a bank account includes its


account number and its current balance
The behaviors associated with a bank account
include deposits and withdrawals
Using new operator
Rectangle r1; ----declare
r1 = new Rectangle(); -----instantiate

Methods
Represents behavior of objects
Consists of four parts:

Method return type


Method name
Parameter list
Method body

General form of method declaration:


type methodname (parameter-list)
{
method-body;
}
Accessing class members:
objectname.variable = value;
objectname.methodname(parameter-list);

Constructors [4M]
Special type of method hat enables an object
to initialize itself when it is created.
Same name as classname
Do not specify return type bcoz always return
instance of class
It is immediately called as soon as object is
created before new operator completes.
Types:
Default
parameterized and
copy constructor.

Examples: area of rectangle

Copy constructor
class Student{
int id; String name;
Student(int i, String n){
id = i; name = n;
}
Student(Student s){
id = s.id; name =s.name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student s1 = new Student(111,abc");
Student s2 = new Student(s1);
s1.display(); s2.display();
}
}

Nesting of Methods
If a method in java calls a method in the same class
Dot operator is not needed
class Demo{
int a=10,b=20;
void display() {
S.o.p(Numbers are:+a+ and +b);
}
void add(){
display();
S.o.p(Addition is:+(a+b));
}
}
class DemoMain{
public static void main(String args[]){
Demo d1 = new Demo();
d1.add();
}}

this keyword[2M]
this is a keyword in Java which can be used inside the
Method or constructor of Class.
It(this) works as a reference to the current Object
whose Method or constructor is being invoked.
Example:
Class Demo {
int variable = 5;
public static void main(String args[]) {
Demo obj = new Demo();
obj.method(20);
}
void method(int variable) {
variable = 10;
S.o.p("Value of Instance var :" + this.variable);
S.o.p("Value of Local var :" + variable);
}
}

Command Line Arguments


Passing info. Into a program while we run it.
It directly follows the programs name on
command line when it is executed.
They are stored as strings in an array of type
String passed to the args parameter of main()
method
Stored at: args[0], args[1] and so on.
Example:
WAP to accept two integer nos using command line and
print their addition [4M]

int sum = Integer.parseInt(args[0]) +


Integer.parseInt(args[1]);

Garbage Collection [4M]


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming
the runtime unused memory automatically.
In other words, it is a way to destroy the
unused objects.
To do so, free() function is used in C language
and delete() in C++. But, in java it is
performed automatically. So, java provides
better memory management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of
JVM) so we don't need to make extra efforts.

Garbage Collection [4M]


There are many ways by which an object can
be unreferenced:
By nulling the reference:
Employee e=new Employee();
e=null;
By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;

When no references to an object exist, then it


is assumed to be no longer needed and
memory occupied by it can be reclaimed.
Garbage collector can be invoked explicitly by
calling from our program.

finalize() and gc() method[4M]


The gc() method is used to invoke the
garbage
collector
to
perform
cleanup
processing.
The gc() is found in System and Runtime
classes.
public static void gc(){}

Garbage collection is performed by a thread


called Garbage Collector(GC) which calls the
finalize() method before object is garbage
collected.
This method can be used to perform cleanup
processing.
This method is defined in Object class
protected void finalize(){}

finalize() and gc() method[4M]


The Garbage collector of JVM collects only those
objects that are created by new keyword. So if an
object is created without new, then we can use
finalize method to perform cleanup processing.
Finalize() method is used sometimes when an object
is holding some non-Java resource such as file handle
then to make sure these resources are freed before an
object is destroyed.
public class Demo1{
public void finalize(){
System.out.println("object is garbage collected");
}
public static void main(String args[]){
Demo1 d1=new Demo1();
d1=null;
System.gc();
}
}

Object class
The java.lang.Object class is the parent class
of all the classes in java by default. In other
words, it is the topmost class of java.
The Object class is beneficial if you want to
refer any object whose type you don't know.
Constructor : Object()
All objects, including arrays, implement the
methods of this class.

Methods of Object class


protected Object clone()
This method creates and returns a copy of this object.
boolean equals(Object obj)
indicates if some other object is "equal to" this one.
protected void finalize()
int hashCode()
This method returns a hash code value for the object.
void notify()
This method wakes up a single thread that is waiting on
this object's monitor.
void notifyAll()
wakes up all threads that are waiting.
String toString()
returns a string representation of the object.
void wait()
causes the current thread to wait until another thread
invokes the notify() or notifyAll() method for this object.

Package
A java package is a group of similar types of
classes, interfaces and sub-packages.
Package in java can be categorized in two
form, built-in package and user-defined
package.
There are many built-in packages such as
java, lang, awt, swing, net, io, util, sql etc.
Advantage of Java Package
easily maintained.
provides access protection.

Visibility Control
Java provides a number of access modifiers
to set access levels for classes, variables,
methods and constructors.
The four access levels are:

Visible
Visible
Visible
Visible

Access
Modifier

to
to
to
to

the
the
the
the

package (default).
class only (private).
world (public).
package and all subclasses (protected).

within
class

within
package

outside package
by subclass only

outside
package

Private

Default

Protected

Public

1. Default
Default access modifier means we do not
explicitly declare an access modifier for a
class, field, method, etc.
A variable or method declared without any
access control modifier is available to any
other class in the same package.
Example:
String version = "1.5.1";
boolean processOrder() {
return true;
}
package pack;
class A{
void msg(){System.out.println("Hello");}
}

1. Default (Example)
package pack;
class A{
void msg(){
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
}
}

2. Private
Private access modifier is the most restrictive
access level.
Methods, Variables and Constructors that are
declared private can only be accessed within
the declared class itself.
Class and interfaces cannot be private.
Using the private modifier is the main way
that an object encapsulates itself and hide
data from the outside world.

2. Private (Example)
class A{
private int data=40;
private void msg(){
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
S.o.p(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

3. Public
A class, method, constructor, interface,
fields, etc. declared public can be accessed
from any other class belonging to the Java
Universe.
However if the public class we are trying to
access is in a different package, then the
public class needs to be imported.
Because of inheritance, all public methods
and variables of a class are inherited by its
subclasses.

3. Public (Example)
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

4. Protected
Variables, methods and constructors which
are declared protected in a superclass can be
accessed only by the subclasses in other
package or any class within the package.
The protected access modifier cannot be
applied to class and interfaces.

4. Protected (Example)
package pack;
public class A{
protected void msg(){
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

There is large amount of research and


development going on in this field
whose focus is to deal with these
challenges with a holistic approach
to utilize multi-core processors
more efficiently.

You might also like