0% found this document useful (0 votes)
27 views

Unit2 Java

The document discusses object oriented programming concepts in Java including classes, objects, class fundamentals, creating objects, modifying class attributes, and final keyword. It also covers topics like object characteristics, declaring objects, and initializing objects.

Uploaded by

HASMUKH RUSHABH
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)
27 views

Unit2 Java

The document discusses object oriented programming concepts in Java including classes, objects, class fundamentals, creating objects, modifying class attributes, and final keyword. It also covers topics like object characteristics, declaring objects, and initializing objects.

Uploaded by

HASMUKH RUSHABH
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
You are on page 1/ 70

Object Oriented

Programming with JAVA


SEIT1030
Mrs. Hemangini Amit Patel
P P Savani University
School of Engineering
CE/IT
Unit 2

Object Oriented
Programming Fundamentals
Topics to Be Covered
• Class Fundamentals • Abstract Class and Interfaces

• Object and Object reference • Defining Methods

• Object Life time and Garbage • Method Overloading


Collection
• Dealing with Static Members
• Constructor
• Use of “this” reference
• Access Control
• Use of Modifiers with Classes &
• Modifiers Methods

• Nested class • Generic Class Types

• Inner Class

• Anonymous Classes
Introduction
• We all know that java is pure Object Oriented Programming
Language.
• Class and Object are one of them…
Class Fundamentals
• Class: It is a template that Datatype variable2;
specifies the attributes and //…
behaviour of things or objects. Datatype variable;
return_type
• It is a blueprint or prototype methodname1(parameter list)
from which objects are
{
created.
// body of the method
• A class is the implementation }
of an Abstract Datatype (ADT).
It defines attributes and
return_type
methods which implements the methodnameN(parameter list)
data structure and operation
{
of the ADT, respectively,
// body of the
– Syntax: method
class class_name }
{ }
Datatype variable1;
Class Fundamentals
• A class is declare by using • Methods
keyword “class”. – Syntax:
• The data, or variables, defines Return_type method_name(parameter
list)
within a class are called as an
instance variables. {
// body of the method
• Because each instance of the }
class (that is, each object of
class) contains its own copy of • Here, return type specifies the
these variables. type of data returned by the
method.
• Thus, the data of one object is
separate and unique from the • This can be any valid type.
data of another.
• If method does not return any
• The actual code contains with value, then its return type must
in methods. be void.
• The methods and variables
defined within a class are called
members of a class.
Class Fundamentals
• The name of method specified by method_name.
• This can be any legal identifier other than those already used by
other member within the current scope.
• The parameter list is a sequence of type and identifier pairs
separated by commas.
• Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called.
• It method has no parameters, then the parameter list will be
empty.
Class Fundamentals
• Return value: return(width * height * depth);
– Method that have a return type other }
than void return a value to the calling }
method using the following from the return
statement. • Method call
• Syntax: • Syntax:
– Return value; – Var_name =
– Here, value is the value returned. object_name.method_name(parameter
list);
– Example:
– Example: vol = b1.volume();
– class Box
{ • In above example, b1 is an object and
double width = 1; when volume() is called, it is put on the
right side of an assignment statement.
double height = 2;
double depth = 3; • On the left is a variable, in this case vol,
that will receive the value returned by
volume();
double volume()
{
How to create a class:
• test.java
Class test
{
int x = 5;
}
• Note: File name must be same as your class name.
Create an Object
• test.java
Class test
{
int x = 5;
public static void main(String[] args)
{ This is an object for class test
test t1 = new test();
System.out.println(t1.x);
}
}
Multiple Objects .
(t1 x)

• test.java Assignment operator


Public class test{
int x = 5;
public static void main(String[] args){
Referentia
test t1 = new test(); // object1
l Variable Multiple object
test t2 = new test(); // object2
System.out.println(t1.x);
System.out.println(t2.x);
}
}
Multiple Class Creation
• first.java public class second{
public class first{ public static void main(String[] args){

int x = 10; first f1 = new first();

} first f2 = new first();

System.out.println(f1.x);

f2.x = 20;

System.out.println(f2.x);

}
• second.java
}
• When both files have been compiled:

• Run the second.java file:

• Final output after the execution:


Java Class Attributes
• The referential variable of class • Another term for class
is actually an attributes of the attributes is fields.
class. Or • To access these attributes
• Class attributes are variables simply create an object and
within a class: (E.g.) called them with this object,
test t1 = new test();
• Create a class called “test”
with 2 attributes: x and y: test t2 = new test();
public class test{ System.out.println(t1.x);
int x = 5; System.out.println(t2.y);
int y = 10;
}
Modify Attributes
• You can also modify attribute values:
• Set the value of x to 40 or override the value of x:
Public class test{
int x ; // x = 10
public static void main(String[] args)
{
test t1 = new test();
t1.x = 40; // override the value of x
System.out.println(t1.x);
}
}
Final Key Word
• If you don’t want to override the existing values, declare the attribute
as final:
public class test{
final x = 10;
public static void main(String[] args)
test t1 = new test();
t1.x = 20; // will generate an error: cannot assign a value to a final
variable.
System.out.println(t1.x);
}
• The final keyword is useful when you want a variable to always store the same
value, like PI (3.141459….)
• The final keyword is called a “modifier”.
Object
• It is an instance of a class.
• It is a basic unit of OOP and represents the real life entities.
• A typical Java program creates many objects, which as you
know, interact by invoking methods.
• An object consists of:
– State: It is represented by attributes of an object. It also reflects the
properties of an object.
– Behavior: It is represented by methods of an object. It also reflects the
response of an object with other objects.
– Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Object Characteristics
Object
• For example dog:

• Objects correspond to things found in the real world.


• For example, a graphics program may have objects such as “circle”,
“square”, “menu”.
• An online shopping system might have objects such as “shopping
cart”, “customer”, and “product”.
Declaring Objects (Also called
instantiating a class)
• When an object of a class is created, the class is said to
be instantiated.

• All the instances share the attributes and the behavior of the class.

• But the values of those attributes, i.e. the state are unique for each
object.

• A single class may have any number of instances. (e.g)


Declaring Objects (Also called
instantiating a class)
• As we declare variables like (type name;).

• This notifies the compiler that we will use name to refer to data whose type is
type.

• With a primitive variable, this declaration also reserves the proper amount of
memory for the variable.

• So for reference variable, type must be strictly a concrete class name.

• In general, we can’t create objects of an abstract class or an interface.


Dog tuffy;

• If we declare reference variable(tuffy) like this, its value will be


undetermined(null) until an object is actually created and assigned to it.

• Simply declaring a reference variable does not create an object.


Initializing an object
• The new operator instantiates a class by allocating memory for a new object
and returning a reference to that memory.

• The new operator also invokes the class constructor.

• The object itself created separately .

• (e.g) Scanner sc;


Object
Object
An instance of
a class Person

Class
A template or
Sally blueprint from which
Jim Bob individual objects
are created.
Garbage Collection
• 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, we were using free() function in C language and
delete() in C++.
• But, in java it is performed automatically. So, java provides better
memory management.
Garbage Collection
• 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.

• How can an object be unreferenced?


– There are many ways:
– By nulling the reference
– By assigning a reference to another
– By anonymous object etc.
Garbage Collection
• By Nulling a reference:

• By Assigning a reference to another:

• By Anonymous object:
Garbage Collection
• finalize() method
– The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:

• Note: The Garbage collector of JVM collects only those objects that
are created by new keyword. So if you have created any object
without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
Garbage Collection
• gc() method
– The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.

• Note: Garbage collection is performed by a daemon thread


called Garbage Collector(GC). This thread calls the finalize()
method before object is garbage collected.
Garbage Collection
Constructor
• In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• It calls a default constructor if there is no constructor available in the
class. In such case, Java compiler provides a default constructor by
default.
• There are two types of constructors in Java: no-arg constructor, and
parameterized constructor.
• Note:
– It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
Constructor
• Rules for creating Java Constructor
– Constructor name must be the same as its class name
– A Constructor must have no explicit return type
– A Java constructor cannot be abstract, static, final, and synchronized

• Note: We can use access modifiers while declaring a


constructor. It controls the object creation. In other words, we
can have private, protected, public or default constructor in
Java.
Types of Constructor
• There are two types of constructors in Java:
– Default constructor (no-arg constructor)
– Parameterized constructor
Java Default Constructor
• A constructor is called
"Default Constructor"
when it doesn't have
any parameter.
• Syntax:
<class_name>(){}
• Rule: If there is no
constructor in a class,
compiler automatically
creates a default
constructor.
Java Parameterized Constructor
• A constructor which has a specific number of parameters is
called a parameterized constructor.
• Why use the parameterized constructor?
– The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.
Java Parameterized Constructor(Example)

Note: We can have any


number of parameters in
the constructor.
Constructor Overloading
• In Java, a constructor is just like a method but without return
type. It can also be overloaded like Java methods.
• Constructor overloading in java is a technique of having more
than one constructor with different parameter lists.
• They are arranged in a way that each constructor performs a
different task.
• They are differentiated by the compiler by the number of
parameters in the list and their types.
Constructor Overloading(Example)
Constructor Overloading(Example)
Difference between constructor and
method in Java
Java Constructor Java Method
 A constructor is used to initialize  A method is used to expose the
the state of an object. behavior of an object.
 A constructor must not have a  A method must have a return
return type. type.
 The constructor is invoked  The method is invoked explicitly.
implicitly.
 The Java compiler provides a  The method is not provided by
default constructor if you don't have the compiler in any case.
any constructor in a class.
 The constructor name must be  The method name may or may
same as the class name. not be same as the class name.
Access Control
• Access control is a mechanism, an attribute of encapsulation which restricts
the access of certain members of a class to specific parts of a program.
• Access to members of a class can be controlled using the access modifiers.
• There are four access modifiers in Java. They are:
– public
– protected
– Default
– private

• If the member (variable or method) is not marked as


either public or protected or private, the access modifier for that member will
be default.
• We can apply access modifiers to classes also.
Access Modifier
• The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class.
• We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
– Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
– Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.
– Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
– Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
Access Modifier
• There are many non-access modifiers, such as static, abstract,
synchronized, native, volatile, transient, etc.
• Here, we are going to learn the access modifiers only.
Private
• The private access modifier is accessible only within the class.
• Simple example of private access modifier
• In this example, we have created two classes A and Simple. A
class contains private data member and private method.
• We are accessing these private members from outside the class,
so there is a compile-time error.
Private
Role of Private Constructor
• If you make any class constructor private, you cannot create the
instance of that class from outside the class. For example:
Default
• If you don't use any modifier, it is treated
as default by default. The default modifier is
accessible only within package.
• It cannot be accessed from outside the
package.
• It provides more accessibility than private.
But, it is more restrictive than protected, and
public.
• Example of default access modifier
– In this example, we have created two packages
pack and mypack. We are accessing the A class
from outside its package, since A class is not
public, so it cannot be accessed from outside
the package.
Protected
• The protected access modifier is accessible
within package and outside the package
but through inheritance only.
• The protected access modifier can be
applied on the data member, method and
constructor. It can't be applied on the class.
• It provides more accessibility than the
default modifier.
• Example of protected access modifier
• In this example, we have created the two
packages pack and mypack.
• The A class of pack package is public, so
can be accessed from outside the
package.
• But msg method of this package is declared
as protected, so it can be accessed from
outside the class only through inheritance.
Public
• The public access modifier is accessible everywhere. It has the
widest scope among all other modifiers.
Nested Class & Inner Class
• In Java, it is also possible to nest
classes (a class within a class).
• The purpose of nested classes is to
group classes that belong
together, which makes your code
more readable and maintainable.
• To access the inner class, create
an object of the outer class, and
then create an object of the inner
class:
Private Inner Class
• Unlike a "regular" class, an inner class can be private or
protected. If you don't want outside objects to access the inner
class, declare the class as private:
Private Inner Class
Static Inner Class
• An inner class can also be static, which means that you can
access it without creating an object of the outer class:

Note: just like static


attributes and methods,
a static inner class does
not have access to
members of the outer
class.
Access Outer Class From Inner Class
• One advantage of inner classes, is that they can access
attributes and methods of the outer class:
Anonymous Classes
• Java anonymous inner class is an inner class without a name and
for which only a single object is created.
• An anonymous inner class can be useful when making an
instance of an object with certain "extras" such as overloading
methods of a class or interface, without having to actually
subclass a class.
Dealing with Static Members
Use of ‘this’ reference
Method Creation
Method Overloading
Method Overriding

You might also like