0% found this document useful (0 votes)
12 views46 pages

Unit-3 Java Classes, Objects, Methods

Uploaded by

aaaryasingh1602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views46 pages

Unit-3 Java Classes, Objects, Methods

Uploaded by

aaaryasingh1602
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 46

Class Definition in Java

In object-oriented programming, a class is a basic building block. It can be defined as


template that describes the data and behaviour associated with the class instantiation.
Instantiating is a class is to create an object (variable) of that class that can be used to
access the member variables and methods of the class.

A class can also be called a logical template to create the objects that share common
properties and methods.

For example, an Employee class may contain all the employee details in the form of
variables and methods. If the class is instantiated i.e. if an object of the class is created
(say e1), we can access all the methods or properties of the class.

Defining a Class in Java


Java provides a reserved keyword class to define a class. The keyword must be followed
by the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must 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 surrounded by braces, { }.

Syntax:

1. <access specifier> class class_name


2. {
3. // member variables
4. // class methods
5. }

Java Class Example


Example 1:
Let's consider the following example to understand how to define a class in Java and
implement it with the object of class.

Calculate.java

1. // class definition
2. public class Calculate {
3.
4. // instance variables
5. int a;
6. int b;
7.
8. // constructor to instantiate
9. public Calculate (int x, int y) {
10. this.a = x;
11. this.b = y;
12. }
13.
14. // method to add numbers
15. public int add () {
16. int res = a + b;
17. return res;
18. }
19.
20. // method to subtract numbers
21. public int subtract () {
22. int res = a - b;
23. return res;
24. }
25.
26. // method to multiply numbers
27. public int multiply () {
28. int res = a * b;
29. return res;
30. }
31.
32. // method to divide numbers
33. public int divide () {
34. int res = a / b;
35. return res;
36. }
37.
38.
39. // main method
40. public static void main(String[] args) {
41. // creating object of Class
42. Calculate c1 = new Calculate(45, 4);
43.
44. // calling the methods of Calculate class
45. System.out.println("Addition is :" + c1.add());
46. System.out.println("Subtraction is :" + c1.subtract());
47. System.out.println("Multiplication is :" + c1.multiply());
48. System.out.println("Division is :" + c1.divide());
49.
50.
51. }

Output:
Example 2:
In the following example, we are creating two classes Employee and EmployeeClass. The
Employee class fetches and displays the employee details. In the EmployeeClass, we create
the objects of Employee class and use its methods. Here, we are initializing the objects
using the class constructor.

EmployeeClass.java

1. // class to get the employee details


2. class Employee {
3. // declaring variables
4. int emp_id;
5. String name;
6. String dept;
7. float salary;
8.
9. // method to initialize the variables
10. void add_info (int id, String n, String d, float sal) {
11. this.emp_id = id;
12. this.name = n;
13. this.dept = d;
14. this.salary = sal;
15. }
16.
17. // method to display the employee details
18. void display() {
19. System.out.println("Employee id: " + emp_id );
20. System.out.println("Employee name: " + name );
21. System.out.println("Employee department: " + dept );
22. System.out.println("Employee salary: " + salary );
23. }
24. }
25.
26. public class EmployeeClass {
27. public static void main(String[] args) {
28. // creating objects of class Employee
29. Employee e1 = new Employee();
30. Employee e2 = new Employee();
31. Employee e3 = new Employee();
32.
33. // calling the methods
34. e1.add_info (101, "Naman", "Salesforce", 45000);
35. e2.add_info (102, "Riya", "Tax", 25000);
36. e3.add_info (103, "Anu", "Development", 55000);
37.
38. e1.display();
39. e2.display();
40. e3.display();
41. }
42. }

Output:
Object in Java
Java is an object-oriented programming language, which means that objects play a central
role in its design. Fundamental things in Java that contain data and behaviours are called
objects. For Java code to be efficient and modular, understanding objects is crucial. We
will examine objects in this article, including what they are, how they are made, and how
Java objects interact with one another.

What is an Object?
An object in Java is an instance of a class. A class is a model or a template that specifies
the composition and operation of objects. It describes the possible data and behaviours
that an object of that class can have in terms of properties and methods. Consider a class
as the design for a house, and an object as the actual house constructed from that design.

Creating Objects in Java


In Java, the new keyword must be used in conjunction with the class name and brackets
to create an object. If the class constructor calls for them, the brackets may be filled with
parameters or left empty. When an object is formed, a particular method called the
constructor is called, and it is in charge of initialising the object's state.

Here is an illustration of how to make an object of the class "Person":

1. Person person = new Person();


In this example, we create a new object of the Person class and assign it to the variable
person.

Object State and Behavior


State and behaviour are the two main components of objects. An object's state or
properties are represented by its data, while its behaviour is a representation of the
actions or operations the object is capable of.

Instance variables, usually referred to as fields, are used to specify the state. These
variables hold the information connected to an object. To express the state of a person
object, for instance, a Person class might have instance variables for name, age, and
address.

Methods determine behaviour. The functions known as methods carry out particular
actions on an object or give access to its data. To change the state or obtain data for an
object, a Person class can have methods like getName(), getAge(), and setAddress().

Object Interactions
By using each other's methods or data, objects communicate with one another. The ability
to create complex systems is enabled by this interaction, which is at the core of object-
oriented programming.

Filename: Car.java

1. public class Car {


2. private String brand;
3. private String model;
4. private int year;
5.
6. // Constructor
7. public Car(String brand, String model, int year) {
8. this.brand = brand;
9. this.model = model;
10. this.year = year;
11. }
12.
13. // Getter methods
14. public String getBrand() {
15. return brand;
16. }
17.
18. public String getModel() {
19. return model;
20. }
21.
22. public int getYear() {
23. return year;
24. }
25.
26. // Setter methods
27. public void setBrand(String brand) {
28. this.brand = brand;
29. }
30.
31. public void setModel(String model) {
32. this.model = model;
33. }
34.
35. public void setYear(int year) {
36. this.year = year;
37. }
38.
39. // Other methods
40. public void startEngine() {
41. System.out.println("The " + brand + " " + model + " engine has started.");
42. }
43.
44. public void stopEngine() {
45. System.out.println("The " + brand + " " + model + " engine has stopped.");
46. }
47.
48. // Main method
49. public static void main(String[] args) {
50. // Create an object of Car
51. Car myCar = new Car("Toyota", "Camry", 2020);
52.
53. // Access object properties
54. System.out.println("Brand: " + myCar.getBrand());
55. System.out.println("Model: " + myCar.getModel());
56. System.out.println("Year: " + myCar.getYear());
57.
58. // Modify object properties
59. myCar.setYear(2022);
60.
61. // Call object methods
62. myCar.startEngine();
63. myCar.stopEngine();
64. }
65. }

Output:

Brand: ToyotaModel: Camry


Year: 2020
The Toyota Camry engine has started.

In this illustration, a car object is represented by the Car class. In addition to constructor,
getter, and setter methods for accessing and changing the object's properties, it also
provides the methods startEngine and stopEngine for taking actions on the car object.
Private instance variables for the brand, model, and year are also included. The main
method explains how to create, access, change, and call the methods of a Car object.

Conclusion
The fundamental units of a Java programme are objects. They provide a modular and
structured approach to programming by encapsulating data and behaviour. You may use
the power of object-oriented programming to construct reliable and maintainable Java
applications by knowing how to create objects, define their state and behaviour, and
create interactions between them.

Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code.
We can also easily modify code using methods. In this section, we will learn what is a
method in Java, types of methods, method declaration, and how to call a method in
Java.

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. If you want to read more about
the main() method, go through the link https://www.javatpoint.com/java-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.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }

Output:

The maximum number is: 9

In the above example, we have used three predefined methods main(),


print(), and max(). We have used these methods directly without declaration because
they are predefined. The print() method is a method of PrintStream class that prints the
result on the console. The max() method is a method of the Math class that returns the
greater of two numbers.

We can also see the method signature of any predefined method by using the
link https://docs.oracle.com/. When we go through the link and see the max() method
signature, we find the following:
In the above method signature, we see that the method signature has access
specifier public, non-access modifier static, return type int, method
name max(), parameter list (int a, int b). In the above example, instead of defining the
method, we have just invoked the method. This is the advantage of a predefined method.
It makes programming less complicated.

Similarly, we can also see the method signature of the print() method.

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.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we will
define the method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

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.

How to Call or Invoke a User-defined Method

Once we have defined a method, it should be called. The calling of a method in a program
is simple. When we call or invoke a user-defined method, the program control transfer to
the called method.

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }

In the above code snippet, as soon as the compiler reaches at


line findEvenOdd(num), the control transfer to the method and gives the output
accordingly.

Let's combine both snippets of codes in a single program and execute it.

EvenOdd.java

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }

Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

Let's see another program that return a value to the calling method.

In the following program, we have defined a method named add() that sum up the two
numbers. It has two parameters n1 and n2 of integer type. The values of n1 and n2
correspond to the value of a and b, respectively. Therefore, the method adds the value of
a and b and store it in the variable s and returns the sum.
Addition.java

1. public class Addition


2. {
3. public static void main(String[] args)
4. {
5. int a = 19;
6. int b = 5;
7. //method calling
8. int c = add(a, b); //a and b are actual parameters
9. System.out.println("The sum of a and b is= " + c);
10. }
11. //user defined method
12. public static int add(int n1, int n2) //n1 and n2 are formal parameters
13. {
14. int s;
15. s=n1+n2;
16. return s; //returning the sum
17. }
18. }

Output:

The sum of a and b is= 24

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


Display.java

1. public class Display


2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static method.");
10. }
11. }

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.

InstanceMethodExample.java

1. public class InstanceMethodExample


2. {
3. public static void main(String [] args)
4. {
5. //Creating an object of the class
6. InstanceMethodExample obj = new InstanceMethodExample();
7. //invoking instance method
8. System.out.println("The sum is: "+obj.add(12, 13));
9. }
10. int s;
11. //user-defined method because we have not used static keyword
12. public int add(int a, int b)
13. {
14. s = a+b;
15. //returning the sum
16. return s;
17. }
18. }

Output:

The sum is: 25

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the instance variable(s) is known as the
accessor method. We can easily identify it because the method is prefixed with the
word get. It is also known as getters. It returns the value of the private field. It is used to
get the value of the private field.

Example

1. public int getId()


2. {
3. return Id;
4. }

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

1. public void setRoll(int roll)


2. {
3. this.roll = roll;
4. }

Example of accessor and mutator method

Student.java

1. public class Student


2. {
3. private int roll;
4. private String name;
5. public int getRoll() //accessor method
6. {
7. return roll;
8. }
9. public void setRoll(int roll) //mutator method
10. {
11. this.roll = roll;
12. }
13. public String getName()
14. {
15. return name;
16. }
17. public void setName(String name)
18. {
19. this.name = name;
20. }
21. public void display()
22. {
23. System.out.println("Roll no.: "+roll);
24. System.out.println("Student name: "+name);
25. }
26. }
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

1. abstract void method_name();

Example of abstract method

Demo.java

1. abstract class Demo //abstract class


2. {
3. //abstract method declaration
4. abstract void display();
5. }
6. public class MyClass extends Demo
7. {
8. //method impelmentation
9. void display()
10. {
11. System.out.println("Abstract method?");
12. }
13. public static void main(String args[])
14. {
15. //creating object of abstract class
16. Demo obj = new MyClass();
17. //invoking abstract method
18. obj.display();
19. }
20. }
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();

Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name
of the memory location. It is a combination of "vary + able" which means its value can be
changed.
1. int data=50;//Here data is variable

Types of Variables
There are three types of variables in Java:

ADVERTISEMENT

ADVERTISEMENT

o local variable
o instance variable
o static variable
1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware
that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.

Example to understand the types of variables in java


1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

Java Variable Example: Add Two Numbers


1. public class Simple{
2. public static void main(String[] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. System.out.println(c);
7. }
8. }

Output:

20
Java Variable Example: Widening
1. public class Simple{
2. public static void main(String[] args){
3. int a=10;
4. float f=a;
5. System.out.println(a);
6. System.out.println(f);
7. }}

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


1. public class Simple{
2. public static void main(String[] args){
3. float f=10.5f;
4. //int a=f;//Compile time error
5. int a=(int)f;
6. System.out.println(f);
7. System.out.println(a);
8. }}

Output:

10.5
10

Java Variable Example: Overflow


1. class Simple{
2. public static void main(String[] args){
3. //Overflow
4. int a=130;
5. byte b=(byte)a;
6. System.out.println(a);
7. System.out.println(b);
8. }}

Output:

130
-126

Java Variable Example: Adding Lower Type


1. class Simple{
2. public static void main(String[] args){
3. byte a=10;
4. byte b=10;
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int
6. byte c=(byte)(a+b);
7. System.out.println(c);
8. }}

Output:

20

Java Collection add() method


The add() method of Java Collection Interface inserts the specified element in this
Collection. It returns a Boolean value 'true', if it succeeds to insert the element in the
specified collection else it returns 'false'.

Syntax

1. public boolean add(E e)

Parameters
The parameter 'e' represents the element to be added in the Collection.

Return
The add() method returns a Boolean value 'true', if the specified element is not null and
this collection has successfully changed as a result of the call.

Throws
The add() method throws:

ADVERTISEMENT

UnsupportedOperationException - if the add operation is not supported by this collection

ClassCastException- if the class of the specified element prevents it from being added to
this collection.

NullPointerException- if the specified element is null and this collection does not allow
null elements

IllegalArgumentException- if some property of the element prevents it from being added


to this collection

IllegalStateException- if the element cannot be inserted at this time due to some insertion
restrictions

Example 1
1. import java.util.HashSet;
2. import java.util.Set;
3. public interface JavaCollectionAddExample1 {
4. public static void main(String[] args) {
5. Set<Integer> set = new HashSet<>();
6. //add integer values in this collection
7. set.add(34);
8. set.add(12);
9. set.add(45);
10. System.out.print("The elements in Collection : ");
11. System.out.println(set);
12. }
13. }
Output:

The elements in Collection : [34, 12, 45]

Example 2
1. import java.util.HashSet;
2. import java.util.Set;
3. public class JavaCollectionAddExample2 {
4. public static void main(String[] args) {
5. //passing string values
6. Set<String> set = new HashSet<>();
7. //add String values in this collection
8. set.add("Prena");
9. set.add("Anurag");
10. set.add("Bajaj");
11. set.add("Dhruv");
12. System.out.print("The elements in Collection : ");
13. System.out.println(set);
14. }
15. }

Output:

The elements in Collection : [Anurag, Dhruv, Prena, Bajaj]

Example 3
1. import java.util.*;
2. public class JavaCollectionAddExample3 {
3. public static void main(String[] args) {
4. //passing string values
5. List<Integer> set = new ArrayList<Integer>();
6. //add String values in this collection
7. set.add(12);
8. //passing null element
9. set.add(null);
10. set.add(0);
11. set.add(5);
12. System.out.print("The elements in Collection : ");
13. System.out.println(set);
14. }
15. }

Output:

The elements in Collection : [12, null, 0, 5]

Example 4
1. import java.util.concurrent.ConcurrentLinkedQueue;
2. public class JavaCollectionAddExample4 {
3. public static void main(String[] args) {
4. //throw NullPointerException as it does not allow null elements
5. ConcurrentLinkedQueue<Integer> set = new ConcurrentLinkedQueue<>();
6. //add String values in this collection
7. set.add(12);
8. //passing null element
9. set.add(null);
10. set.add(0);
11. set.add(5);
12. set.add(45);
13. System.out.print("The elements in Collection : ");
14. System.out.println(set);
15. }
16. }

Output:

Exception in thread "main" java.lang.NullPointerException


at
java.util.concurrent.ConcurrentLinkedQueue.checkNotNull(ConcurrentLinkedQueue
.java:920)
at
java.util.concurrent.ConcurrentLinkedQueue.offer(ConcurrentLinkedQueue.java:3
27)
at
java.util.concurrent.ConcurrentLinkedQueue.add(ConcurrentLinkedQueue.java:297
)
at
com.javaTpoint.JavaCollectionAddExample4.main(JavaCollectionAddExample4.java:
13)

If any of the specified element in this queue is null, it will give NullPointerException as
described above.

How to Create Object in Java


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.

o Using new Keyword


o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization

Using new Keyword


Using the new keyword is the most popular way to create an object or instance of the
class. When we create an instance of the class by using the new keyword, it allocates
memory (heap) for the newly created object and also returns the reference of that object
to that memory. The new keyword is also used to create an array. The syntax for creating
an object is:

1. ClassName object = new ClassName();

Let's create a program that uses new keyword to create an object.

CreateObjectExample1.java

1. public class CreateObjectExample1


2. {
3. void show()
4. {
5. System.out.println("Welcome to javaTpoint");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. obj.show();
13. }
14. }

Output:

Welcome to javaTpoint

By using the new keyword, we can also invoke the constructor (default or parametrized)
of the class.

CreateObjectExample2.java

1. public class CreateObjectExample2


2. {
3. //constructor of the class
4. CreateObjectExample2()
5. {
6. System.out.println("Welcome to javaTpoint");
7. }
8. public static void main(String[] args)
9. {
10. //creating an object using new keyword
11. CreateObjectExample2 obj = new CreateObjectExample2();
12. }
13. }
Output:

Welcome to javaTpoint

Using clone() Method


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.

Note: The method creates a copy of the object not a new object.

Syntax:

1. protected Object clone() throws CloneNotSupportedException

We use the following statement to create a new object.

1. ClassName newobject = (ClassName) oldobject.clone();

CreateObjectExample3.java

1. public class CreateObjectExample3 implements Cloneable


2. {
3. @Override
4. protected Object clone() throws CloneNotSupportedException
5. {
6. //invokes the clone() method of the super class
7. return super.clone();
8. }
9. String str = "New Object Created";
10. public static void main(String[] args)
11. {
12. //creating an object of the class
13. CreateObjectExample3 obj1 = new CreateObjectExample3();
14. //try catch block to catch the exception thrown by the method
15. try
16. {
17. //creating a new object of the obj1 suing the clone() method
18. CreateObjectExample3 obj2 = (CreateObjectExample3) obj1.clone();
19. System.out.println(obj2.str);
20. }
21. catch (CloneNotSupportedException e)
22. {
23. e.printStackTrace();
24. }
25. }
26. }

Output:

New Object Created

Using newInstance() Method of Class class


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.

Syntax:

1. public T newInstance() throws InstantiationException, IllegalAccessException

It throws the IllegalAccessException, InstantiationException,


ExceptionInInitializerError exceptions.

AD

We can create an object in the following ways:

1. ClassName object = ClassName.class.newInstance();

Or
1. ClassName object = (ClassName) Class.forName("fully qualified name of the class
").newInstance();

In the above statement, forName() is a static method of Class 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.

AD

CreateObjectExample4.java

1. public class CreateObjectExample4


2. {
3. void show()
4. {
5. System.out.println("A new object created.");
6. }
7. public static void main(String[] args)
8. {
9. try
10. {
11. //creating an instance of Class class
12. Class cls = Class.forName("CreateObjectExample4");
13. //creates an instance of the class using the newInstance() method
14. CreateObjectExample4 obj = (CreateObjectExample4) cls.newInstance();
15. //invoking the show() method
16. obj.show();
17. }
18. catch (ClassNotFoundException e)
19. {
20. e.printStackTrace();
21. }
22. catch (InstantiationException e)
23. {
24. e.printStackTrace();
25. }
26. catch (IllegalAccessException e)
27. {
28. e.printStackTrace();
29. }
30. }
31. }

Output:

A new object created.


AD

Using newInstance() Method of Constructor class


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:

1. public T newInstance(Object... initargs) throws InstantiationException, IllegalAcce


ssException, IllegalArgumentException, 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, InvocationTargetException, ExceptionInInitializerError
Exceptions.
We can create an object in the following way:

1. Constructor<Employee> constructor = Employee.class.getConstructor();


2. Employee emp3 = constructor.newInstance();

Let's create a program that creates an object using the newInstance() method.

CreateObjectExample5.java

1. import java.lang.reflect.*;
2. public class CreateObjectExample5
3. {
4. private String str;
5. CreateObjectExample5()
6. {
7. }
8. public void setName(String str)
9. {
10. this.str = str;
11. }
12. public static void main(String[] args)
13. {
14. try
15. {
16. Constructor<CreateObjectExample5> constructor = CreateObjectExample5.class.getDecl
aredConstructor();
17. CreateObjectExample5 r = constructor.newInstance();
18. r.setName("JavaTpoint");
19. System.out.println(r.str);
20. }
21. catch (Exception e)
22. {
23. e.printStackTrace();
24. }
25. }
26. }
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.

Serialization: The writeObject() method of the ObjectOutputStream class is used to


serialize an object. It sends the object to the output stream.

Syntax:

1. public final void writeObject(object x) throws IOException

Deserialization: The method readObject() of ObjectInputStream class is used to


deserialize an object. It references objects out of a stream.

Syntax:

1. public final Object readObject() throws IOException,ClassNotFoundException


Note: Make the filed static or transient if we do not want to include a field as a part of
the object. It will not include in the serialization process.

Let's understand the serialization and deserialization through a program.

Employee.java

1. import java.io.Serializable;
2. public class Employee implements Serializable
3. {
4. int empid;
5. String empname;
6. public Empoyee(int empid, String empname)
7. {
8. this.empid = empid;
9. this.empname = empname;
10. }
11. }

We have created a class named Employee whose object is to be serialized and


deserialized.

Serialization of Java Object:


In the following program, we have serialized an object of Employee class by using
the writeObject() method of the ObjectOutputStream class. The state of the object is
saved in the employee.txt file.

SerializationExample.java

1. import java.io.*;
2. class SerializationExample
3. {
4. public static void main(String args[])
5. {
6. Try
7. {
8. //Creating the object
9. Employee emp = new Employee(198054,"Andrew");
10. //Creates a stream and writes the object
11. FileOutputStream fout=new FileOutputStream("employee.txt");
12. ObjectOutputStream out=new ObjectOutputStream(employeeout);
13. out.writeObject(emp);
14. out.flush();
15. //closes the output stream
16. out.close();
17. System.out.println("Successfully Created");
18. }
19. catch(Exception e)
20. {
21. System.out.println(e);
22. }
23. }
24. }

Output:

Successfully Created

Deserialization of Java Object:


In the following program, we going to deserialize an object that we have serialized in the
above program.

DeserializationExample.java

1. import java.io.*;
2. class DeserializationExample
3. {
4. public static void main(String args[])
5. {
6. try
7. {
8. //Creating a stream to read the object
9. ObjectInputStream in=new ObjectInputStream(new FileInputStream("employee.t
xt"));
10. Employee e=(Employee)in.readObject();
11. //prints the data of the serialized object
12. System.out.println(e.empid+" "+e.empname);
13. //closing the input stream
14. in.close();
15. }
16. catch(Exception e)
17. {
18. System.out.println(e);
19. }
20. }
21. }

Output:

198054 Andrew

In the above five methods, we have noticed that the new keyword and
both newInstance() methods use the constructor to create objects, while the rest two
methods do not use the constructor.

Access Modifiers in Java


1. Private access modifier
2. Role of private constructor
3. Default access modifier
4. Protected access modifier
5. Public access modifier
6. Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access modifiers.

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.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. 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.
3. 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.
4. 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.

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.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

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.

1. class A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

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:

1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
Note: A class cannot be private or protected except nested class.

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.

1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

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.

Example of protected access modifier

AD
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.

1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
Output:Hello

4) Public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

Example of public access modifier

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2.
3. package mypack;
4. import pack.*;
5.
6. class B{
7. public static void main(String args[]){
8. A obj = new A();
9. obj.msg();
10. }
11. }
Output:Hello

Java Access Modifiers with Method Overriding


If you are overriding any method, overridden method (i.e. declared in subclass) must not
be more restrictive.

1. class A{
2. protected void msg(){System.out.println("Hello java");}
3. }
4.
5. public class Simple extends A{
6. void msg(){System.out.println("Hello java");}//C.T.Error
7. public static void main(String args[]){
8. Simple obj=new Simple();
9. obj.msg();
10. }
11. }

The default modifier is more restrictive than protected. That is why, there is a compile-
time error.

You might also like