Java Unit 2
Java Unit 2
Class:
A class in JAVA is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can be accessed and
used by creating an instance of that class. A Java class is like a blueprint for an object.
For Example:
Consider the Class of Cars. There may be many cars with different names and brand but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
A Class is a user defined data-type which has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions defines
the properties andbehavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can be apply brakes, increase speed etc.
Create a class called "MyClass":
public class MyClass {// The class
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Object In Java :
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).
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the 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.
The object is a basic building block of an OOPs language. In Java, we cannot execute any program
without creating an object. There is various way to create an object in Java
Java provides five ways to create an object.
Using new Keyword
Using clone() method
Using newInstance() method of the Class class
Using newInstance() method of the Constructor class
Using Deserialization
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.
The class members are declared in the body of a class. These may comprise fields (variables in a
class). methods, nested classes, and interfaces. The members of a class comprise the members declared
in the class as well as the members inherited from a super class. The scope of all the members extends to
the entire class body.
The fields comprise two types of variables
1. Non Static variables : These include instance and local variables and vanes in scope and value.
(a) Instance variables: These variables are individual to an object and an object keeps a
copy of these variables in its memory.
(b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables ( Static Variables) : These variables are also qualified as static variables. The
values of these variables are common to all the objects of the class. The class keeps only one copy of
these variables and all the objects share the same copy. As class variables belong to the whole
class, these are also called class variables.
Example:
class CustomerId
{
static int count=0; // staticvariable
int id; // instancevariable
CustomerId() // Constructor
{
count++;
JAVA PROGRAMMING 3 KKVPRASAD@CSE
id = count ;
}
int getId() // Method
{
return id;
}
int localVar()
{
int a=10; //Local variable
return a;
}
} class
Application
{ public static void main(String[]args)
{
CustomerId obj = new CustomerId();
System.out.println("Customer Id = " + obj.getId()); System.out.println("Local
Variable = " + obj.localVar());
}
}
Output:
Customer Id = 1
Local Variable = 10
The object is a basic building block of an OOPs language. In Java, we cannot execute any program
without creating an object. There is various way to create an object in Java that we will discuss in this
section, and also learn how to create an object in Java.
Java provides five ways to create an object.
Using new Keyword
Using clone() method
Using newInstance() method of the Class class
Using newInstance() method of the Constructor class
Using Deserialization
The clone() method is the method of Object class. It creates a copy of an object and returns the same
copy. The JVM creates a new object when the clone() method is invoked. It copies all the content of the
previously created object into new one object. Note that it does not call any constructor.
We must implement the Cloneable interface while using the clone() method. The method
throws CloneNotSupportedException exception if the object's class does not support the Cloneable interface.
The subclasses that override the clone() method can throw an exception if an instance cannot be cloned.
Syntax:
ClassName newobject = (ClassName) oldobject.clone();
CreateObjectExample3.java
public class CreateObjectExample3 implements Cloneable
{
@Override
protected Object clone() throws CloneNotSupportedException
{
//invokes the clone() method of the super class
return super.clone();
}
String str = "New Object Created";
public static void main(String[] args)
{
//creating an object of the class
CreateObjectExample3 obj1 = new CreateObjectExample3();
//try catch block to catch the exception thrown by the method
try
{
//creating a new object of the obj1 suing the clone() method
CreateObjectExample3 obj2 = (CreateObjectExample3) obj1.clone();
System.out.println(obj2.str);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
} } }
Output:
New Object Created
The newInstance() method of the Class class is also used to create an object. It calls the default
constructor to create the object. It returns a newly created instance of the class represented by the object. It
internally uses the newInstance() method of the Constructor class.
In the above statement, forName() is a static method of Class. It parses a parameter className of
type String.
It returns the object for the class with the fully qualified name. It loads the class but does not create
any object.
It throws ClassNotFoundException if the class cannot be loaded and LinkageError
if the linkage fails.
To create the object, we use the newInstance() method of the Class class. It works only when we
know the name of the class and the class has a public default constructor.
In the following program, we have creates a new object using the newInstance() method.
CreateObjectExample4.java
It is similar to the newInstance() method of the Class class. It is known as a reflective way to create
objects. The method is defined in the Constructor class which is the class of java.lang.reflect package. We
can also call the parameterized constructor and private constructor by using the newInstance() method. It is
widely preferred in comparison to newInstance() method of the Class class.
Syntax:
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArg
umentException, InvocationTargetException
The method parses an array of Objects as an argument. The values of primitive types wrapped in a
wrapper Object of the appropriate type. It returns a new object created by calling the constructor. It
throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTarget
Exception, ExceptionInInitializerError Exceptions.
We can create an object in the following way:
CreateObjectExample5.java
import java.lang.reflect.*;
public class CreateObjectExample5 {
private String str;
CreateObjectExample5()
{ }
public void setName(String str)
{
this.str = str;
}
public static void main(String[] args)
{
try
{
Constructor<CreateObjectExample5> constructor = CreateObjectExample5.class.get
DeclaredConstructor();
CreateObjectExample5 r = constructor.newInstance();
r.setName("JavaTpoint");
System.out.println(r.str);
}
catch (Exception e)
{
e.printStackTrace();
} } }
Output:
JavaTpoint
Using Deserialization
In Java, serialization is the process of converting an object into a sequence of byte-stream. The
reverse process (byte-stream to object) of serialization is called deserialization. The JVM creates a new
object when we serialize or deserialize an object. It does not use constructor to create an object. While using
deserialization, the Serializable interface (marker interface) must be implemented in the class.
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifier 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.
1) 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.
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();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
} }
2) 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.
//save by A.java
package pack;
class A{
void msg(){
System.out.println("Hello");} }
JAVA PROGRAMMING 9 KKVPRASAD@CSE
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
} }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
3) 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 modifer.
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.
//save by A.java
package pack;
public class A{
protected void msg(){
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
} }
4) Public :
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
In the above example, we have private variables named age and name. Here, we are trying to access
the private variables from other class named Main.
We have used the getter and setter method to access the private variables. Here,
the setter methods setAge() and setName() initializes the private variables
the getter methods getAge() and getName() returns the value of private variables
There are three advantages of inner classes in Java. They are as follows:
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.
Sometimes users need to program a class in such a way so that no other class can access it.
Therefore, it would be better if you include it within other classes.
If all the class objects are a part of the outer object then it is easier to nest that class inside the outer
class. That way all the outer class can access all the objects of the inner class.
Writing a class within another is allowed in Java. The class written within is called the nested class, and the
class that holds the inner class is called the outer class. Nested classes are divided into two types −
Non-static nested classes (Inner Classes) − These are the non-static members of a class.
Static nested classes − These are the static members of a class.
Following are the types of Nested classes in Java −
Example
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}}
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}}
Output : This is an inner class.
Example
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}}
Output
This is my nested class
The most common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
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:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
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.
JAVA PROGRAMMING 21 KKVPRASAD@CSE
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:
Predefined Method
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.
Demo.java
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.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
JAVA PROGRAMMING 22 KKVPRASAD@CSE
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output 1:
Enter the number: 12
12 is even
Output 2:
Enter the number: 99
99 is odd
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.
Example:
public class Student {
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
In Java we can pass objects as argument. In the following Java example, we a have a class with two
instance variables name and age and a parameterized constructor initializing these variables.
We have a method coypObject() which accepts an object of the current class and initializes the
instance variables with the variables of this object and returns it.
In the main method we are instantiating the Student class and making a copy by passing it as an
argument to the coypObject() method.
import java.util.Scanner;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public Student copyObject(Student std){
this.name = std.name;
this.age = std.age;
return std;
}
public void displayData(){
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("Enter your name : ");
String name = sc.next();
System.out.println("Enter your age : ");
int age = sc.nextInt();
Student std = new Student(name, age);
System.out.println("Contents of the original object");
std.displayData();
System.out.println("Contents of the copied object");
Student copyOfStd = new Student().copyObject(std);
copyOfStd.displayData();
}
}
Output
Enter your name : Krishna
Enter your age : 20
Contents of the original object
Name : Krishna
Age : 20
Contents of the copied object
Name : Krishna
Age : 20
Access modifiers are keywords that can be used to control the visibility of fields, methods, and
constructors in a class. The four access modifiers in Java are public, protected, default, and private .
Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called recursive method.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
A method can be called by using only its name by another method of the same class that is called
Nesting of Methods. A method of a class can be called only by an object of that class using the dot operator.
So, there is an exception to this. When a method in java calls another method in the same class, it is called
Nesting of methods.
//Nesting of Methods in Java
class demo {
private int m, n;
demo(int x, int y) {
m = x;
n = y;
}
int largest() {
if (m > n)
return m;
else
return n;
}
void display()
{
int large=largest();
System.out.println("The Greatest Number is : "+large);
}
}
public class nested_method {
public static void main(String args[]) {
demo o =new demo(10,20);
o.display();
}
}
Output
The Greatest Number is : 20
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.