Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Department of IT

Java Programming Unit-3 Class , Objects


and Methods
(01IT0404)

By: Prof. Tarannum


Bloch
An object in Java is the physical as well as a logical entity, whereas, a class in
Java is a logical entity only.

An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible object is the banking system.

Object An object has three characteristics:

State: represents the data (value) of an object.


Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which
objects are created. So, an object is the instance(result) of a class.

Object Definitions:
An object is a real-world entity.
An object is a runtime entity.

Object The object is an entity which has state and behavior.


The object is an instance of a class.
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.

A class in Java can contain:


Fields

Class Methods
Constructors
Blocks
Nested class and interface
Instance variable in Java
A variable which is created inside the class but outside the method is known as
an instance variable. Instance variable doesn't get memory at compile time. It
gets memory at runtime when an object or instance is created. That is why it is
known as an instance variable.

Method in Java
Inside Class In Java, a method is like a function which is used to expose the behavior of an
object.

Advantage of Method
Code Reusability
Code Optimization
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.
3 Ways to initialize object
There are 3 ways to initialize object in Java.
By reference variable
By method
By constructor

Object StudentRef.java
StudentMeth.java
Initialize StudentCons.java
Before We Started with the Reference variable we should know about the
following facts.

When we create an object (instance) of class then space is reserved in heap


memory. Let’s understand with the help of an example.
Demo D1 = new Demo();

Now, The space in the heap Memory is created but the question is how to
access that space?.

Object Then, We create a Pointing element or simply called Reference variable which
simply points out the Object(the created space in a Heap Memory).
Reference
Understanding Reference variable

1. Reference variable is used to point object/values.


2. Classes, interfaces, arrays, enumerations, and, annotations are reference
types in Java. Reference variables hold the objects/values of reference types in
Java.
Object 3. Reference variable can also store null value. By default, if no object is passed
to a reference variable then it will store a null value.
Reference 4. You can access object members using a reference variable using dot syntax
<reference variable name >.<instance variable_name / method_name>
In Java, a constructor is a block of codes similar to the
method.

• It is called when an instance of the object is created, and memory is allocated


for the object.
• It is a special type of method which is used to initialize the object.
• Every time an object is created using new() keyword, at
least one constructor is called.

Following are the rules to define a constructor.


Constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized.

There are two types of constructors in Java:


1. Default constructor (no-arg constructor)
2. Parameterized constructor

Check Program : Bike1.java


Constructors
VS
Methods
In Java, we can overload constructors like methods. The constructor overloading
can be defined as the concept of having more than one constructor with different
parameters so that every constructor can perform a different task.

Check ConstructorOverloading.java

Constructor
Overloading
This is a keyword used to refer
reference variable to the
current object of the class.

this
Keyword
A method in Java is a block of code that, when called, performs specific actions
mentioned in it.

For instance, if you have written instructions to draw a circle in the method, it
will do that task. You can insert values or parameters into methods, and they
will only be executed when called. They are also referred to as functions.

The primary uses of methods in Java are:

• It allows code reusability (define once and use multiple times)


Method • You can break a complex program into smaller chunks of code
• It increases code readability
Method Declaration:

You can only create a method within a class. There are a total of six components
included in a method declaration. The components provide various information
about the method.

1. Access specifier: It is used to define the access type of the method. Public: You
can access it from any class Private: You can access it within the class where it is
defined Protected: Accessible only in the same package or other subclasses in

Methods in
another package Default: It is the default access specifier used by the Java compiler
if we don’t mention any other specifiers. It is accessible only from the package
where it is declared
Java 2. ReturnType: It defines the return type of the method. In the above syntax, “int”
is the return type. We can mention void as the return type if the method returns
no value.

3. Method name: It is used to give a unique name to the method. In the above
syntax, “addNumbers” is the method name. This tutorial looks at some tips for
naming a method, shortly.

4. Parameter list: It is a list of arguments (data type and variable name) that will be
used in the method.
Method Declaration:

5. Method signature: You don’t have to do anything additional here. The method
signature is just a combination of the method name and parameter list.

6. Method body: This is the set of instructions enclosed within curly brackets that
the method will perform.

Methods in
Java
If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.

If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Advantage of method overloading


Method overloading increases the readability of the program.

Method There are two ways to overload the method in java

Overloading By changing number of arguments


By changing the data type

Check Programs: OverloadingDemo.java


One type is promoted to another implicitly if no matching datatype is found.
Let's understand the concept by the figure given below:

Method
Overloading
Type
Promotion
byte can be promoted to short, int, long, float or double. The short datatype
can be promoted to int, long, float or double. The char datatype can be
promoted to int,long,float or double and so on.

Check Program: OverloadingCalculation1.java


Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.

Recursion Check Programs: RecursionDemo.java


You can pass objects as arguments in Java.

Check Example: ObjeAsArg.java

Passing
Object to the
method
A method can return an object in a similar manner as that of returning a
variable of primitive types from methods. When a method returns an object,
the return type of the method is the name of the class to which the object
belongs and the normal return statement in the method is used to return the
object.

Check Program: RetObj.java

Returning
Object from
the method
The Java new keyword is used to create an instance of the class. In other words,
it instantiates a class by allocating memory for a new object and returning a
reference to that memory. We can also use the new keyword to create the array
object.

Syntax:
NewExample obj=new NewExample();

new
Points to remember
Operator It is used to create the object.
It allocates the memory at runtime.
All objects occupy memory in the heap area.
It invokes the object constructor.
It requires a single, postfix argument to call the constructor
The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.

The static can be:

Variable (also known as a class variable)


static Method (also known as a class method)
Block

Keyword
1) Java static variable
If you declare any variable as static, it is known as a static variable. The
static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.

The static variable gets memory only once in the class area at the time
of class loading.

static Advantages of static variable


It makes your program memory efficient (i.e., it saves memory).
Keyword Check Program: StaticVariableDemo.java
2) Java static method
If you apply static keyword with any method, it is known as static
method.

• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an
instance of a class.
static • A static method can access static data member and can change the
value of it.
Keyword Restrictions for the static method
1. The static method can not use non static data member or call non-
static method directly.
2. this and super cannot be used in static context.

Check Program: StaticExample.java


3) Java static block
Is used to initialize the static data member.
It is executed before the main method at the time of class loading.

Check Program: StaticBlockDemo.java

static
Keyword
Finalize() is the method of Object class. This method is called just before an
object is garbage collected. finalize() method overrides to dispose system
resources, perform clean-up activities and minimize memory leaks.

Syntax
protected void finalize() throws Throwable

Throwable - the Exception is raised by this method

Check Example: FinaliseDemo.java


finalise( )
method
Java Package
A package is simply a container that groups related types (Java classes,
interfaces, enumerations, and annotations).

Built-in packages are existing java packages that come along with the JDK. For
example, java.lang, java.util, java.io, etc. For example:

Java programming is used by many users worldwide. It provides numerous


packages to solve different problems. To use the Java packages in our programs,
import keyword is used.
import
import java.util.ArrayList; // imports the array list
Statement import java.util.*; // imports all the classes and interfaces
Java Static Import

The Java static import was introduced in JDK version 1.5. With the help of static
import, the static variables and methods of imported classes can be accessed.
We don't need to specify the class name or object name to access the methods
or variables. Using a static import statement saves time because the
programmer isn't required to use the class name or object name again and
again.

Example:
static
import static java.util.Math;
import double rt = sqrt(a);

OR

import java.util.Math;

double rt = Math.sqrt(a);
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

Access
Control
Java Nested class is also known as inner class is a class that is declared inside the
class or interface.

We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.

Syntax of Inner class


class Java_Outer_class{
//code

Nested Class
class Java_Inner_class{
//code
}
}

Advantage of Java inner classes

1. Nested classes represent a particular type of relationship that is it can access


all the members (data members and methods) of the outer class, including
private.
2. Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Difference between nested class and inner class in Java
An inner class is a part of a nested class. Non-static nested classes are known as
inner classes.

Types of Nested classes


There are two types of nested classes non-static and static nested classes. The

Inner Class non-static nested classes are also known as inner classes.

• Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
• Static nested class
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.

In simple words, a class that has no name is known as an anonymous inner class in
Java. It should be used if you have to override a method of class or interface.
Anonymous
Inner Class Java Anonymous inner class can be created in two ways:
1. Class (may be abstract or concrete).
2. Interface

Advantages of Anonymous Classes


In anonymous classes, objects are created whenever they are required. That is,
objects are created to perform some specific tasks.
Check Program: Main.java
END OF UNIT 3
1. Define terms : Class, Object, Instance, Polymorphism, Package
2. What is new ? Explain use of new with example
3. What is reference variable ? Explain importance of reference variable in
terms of memory allocation.
4. Define Constructor. List out the types of constructors. Discuss the
characteristics of constructors.

Sample 5. Which OOP characteristic is represented by constructor overloading.


Define constructor overloading. Explain it with suitable example.
Questions 6. Which OOP characteristic is represented by method overloading. Define
Unit 3 method overloading. Explain it with suitable example. Also discuss about
method overloading with type promotion.
7. What is recursion ? Explain with code snippet.
8. What is this? Explain use of this with example
9. What is static? Explain use of static with example
10. Explain import and static import with suitable code lines
11. What is garbage collection ? Explain role of finialize() method with code
example.
12. What is access Specifiers ? Explain access control mechanism in Java.
13. Explain nested class and with t’s advantages and code example.
14. Explain inner class and anonymous class with it’s advantages and code
example.

Sample 15. Explain object as a method argument and object as a return type of a
method by writing a java program
Questions 16. Explain array as a method argument and array as a return type of a
Unit 3 method by writing a java program
1. Define terms : Array , String, Wrapper class
2. Explain 1D dimensional arrays. Discuss about array declaration, array
initialization and access 1D array elements with suitable example.
3. Explain 2D dimensional arrays. Discuss about array declaration, array
initialization and access 2D array elements with suitable example.
4. What do you mean by jagged array ? Explain with code snippet.

Sample 5. Differentiate between Array and ArrayList class


6. Differentiate between String and StringBuffer class
Questions 7. What is wrapper class? What is the need of wrapper class ? Explain with
Unit 2 example
8. Explain common wrapper class methods with code snippet.
9. Explain String class and it’s in built methods with code snippet
10. Explain String Buffer class and it’s in built methods with code snippet
11. Explain AbstractList class and it’s in built methods with code snippet
12. Explain LinkedList class and it’s in built methods with code snippet
13. Explain vector class and it’s in built methods with code snippet
14. Explain iterative enumeration statements with suitable example.

Sample
Questions
Unit 2

You might also like