BE Java Module - 2
BE Java Module - 2
Introducing Classes:
Class Fundamentals: In Java, classes and objects are basic concepts of Object Oriented
Programming (OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior. For example, the animal
type Dog is a class while a particular dog named Browny is an object of the Dog class.
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. It is a user-defined blueprint or prototype from which objects
are created. For example, Student is a class while a particular student named Raj is an object.
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of Student
Student obj = new Student();
System.out.println(obj.id);
System.out.println(obj.name);
}
}
Components of Java Classes
In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access.
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.
6. Body: The class body is surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provide the state
of the class and its objects, and methods are used to implement the behavior of the class and
its objects.
Objects:
An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. Objects are the instances of a class that are created to use the attributes and methods
of a class. A typical Java program creates many objects, which as you know, interact by
invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior : It is represented by the methods of an object. It also reflects the response
of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object to interact with
other objects.
Example of an object: dog
Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, and “menu”. An online shopping system might have
objects such as “shopping cart”, “customer”, and “product”.
Note: When we create an object which is a non primitive data type, it’s always allocated on
the heap memory.
Declaring Objects
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.
Example:
As we declare variables like (type name;). This notifies the compiler that we will use the
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 variables , the 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 a 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.
/ Class Declaration
// method 1
public String getName() { return name; }
// method 2
public String getBreed() { return breed; }
// method 3
public int getAge() { return age; }
// method 4
public String getColor() { return color; }
Output
Hi my name is tuffy.
My breed,age and color are papillon,5,white
Output
Software name is: Visual studio
Software price is: 0.0
Introducing Methods
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.
The most important method in Java is the main() method.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we
call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
Predefined method:
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the number is even, it prints the
number is even, else prints the number is odd.
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is
the main() method.
Example of static method
public class Display
{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}
Output:
It is an example of a static method.
Instance Method
The method of the class is known as an instance method. It is a non-static method defined
in the class. Before calling or invoking the instance method, it is necessary to create an object
of its class. Let's see an example of an instance method.
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25
Mutator Method: The method(s) read the instance variable(s) and also modify the values.
We can easily identify it because the method is prefixed with the word set. It is also known
as setters or modifiers. It does not return anything. It accepts a parameter of the same data
type that depends on the field. It is used to set the value of the private field.
Example
public void setRoll(int roll)
{
this.roll = roll;
}
Abstract Method
The method that does not has method body is known as abstract method. In other words,
without an implementation is known as abstract method. It always declares in the abstract
class. It means the class itself must be abstract if it has abstract method. To create an abstract
method, we use the keyword abstract.
Syntax
abstract void method_name();
Example of abstract method
abstract class Demo //abstract class
{
//abstract method declaration
abstract void display();
}
public class MyClass extends Demo
{
//method impelmentation
void display()
{
System.out.println("Abstract method?");
}
public static void main(String args[])
{
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}
Output:
Abstract method...
Factory method
It is a method that returns an object to the class to which it belongs. All static methods are
factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance();
Constructors
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 the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
class Ge {
// data members of the class.
String name;
int id;
// Parameterized Constructor
Ge(String name, int id)
{
this.name = name;
this.id = id;
}
// Copy Constructor
Ge(Ge obj2)
{
this.name = obj2.name;
this.id = obj2.id;
}
}
class CopyConstructor{
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
System.out.println("First Object");
Ge ge1 = new Ge("Raj", 24);
System.out.println("Name :" + ge1.name + " and Id :" + ge1.id);
System.out.println();
// Constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}
first.change_name("PQR");
System.out.println("Name has been changed to: "
+ first.get_name());
}
}
Output
Name: RAJ
Age: 18
Name: RAM
Age: 22
Explanation
In the above code, we have defined a Person class with two private fields name and age. We
have defined the Person class constructor to initialize these fields using this keyword. We
have also defined getter and setter methods for these fields which use this keyword to refer to
the current object instance.
In the printDetails() method, we have used this keyword to refer to the current object instance
and print its name, age, and object reference.
In the Main class, we have created two Person objects and called the printDetails() method on
each object. The output shows the name, age, and object reference of each object instance.
class Test {
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
// Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
Output
a = 10 b = 20
// Default constructor
Test()
{
this(10, 20);
System.out.println("Inside default constructor \n");
}
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
System.out.println("Inside parameterized constructor");
}
Output
Inside parameterized constructor
Inside default constructor
3. Using ‘this’ keyword to return the current class instance
// Java code for using 'this' keyword to return the current class instance
class Test {
int a;
int b;
// Default constructor
Test()
{
a = 10;
b = 20;
}
Output
a = 10 b = 20
// Default constructor
Test()
{
a = 10;
b = 20;
}
// main function
public static void main(String[] args)
{
Test object = new Test();
object.get();
}
}
Output
a = 10 b = 20
void display()
{
// calling function show()
this.show();
void show()
{
System.out.println("Inside show function");
}
class A {
B obj;
class B {
int x = 5;
Output
Value of x in Class B : 5
Garbage Collection
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine,
or JVM for short. When Java programs run on the JVM, objects are created on the heap,
which is a portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them to free
up memory.
Finalization
• Just before destroying an object, Garbage Collector calls finalize() method on the
object to perform cleanup activities. Once finalize() method completes, Garbage
Collector destroys that object.
• finalize() method is present in Object class with the following prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for performing our cleanup
activities like closing connection from the database.
1. The finalize() method is called by Garbage Collector, not JVM. However, Garbage
Collector is one of the modules of JVM.
2. Object class finalize() method has an empty implementation. Thus, it is recommended
to override the finalize() method to dispose of system resources or perform other
cleanups.
3. The finalize() method is never invoked more than once for any object.
4. If an uncaught exception is thrown by the finalize() method, the exception is ignored,
and the finalization of that object terminates.