Unit-3 Java Classes, Objects, Methods
Unit-3 Java Classes, Objects, Methods
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.
Syntax:
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
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.
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
Output:
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.
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:
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.
Demo.java
Output:
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.
Let's create a user defined method that checks the number is even or odd. First, we will
define the method.
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.
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. }
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:
Output 2:
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
Output:
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.
Output:
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
Output:
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
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
Student.java
Syntax
Demo.java
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.
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.
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
Output:
10.5
10
Output:
130
-126
Output:
20
Syntax
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
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
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:
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:
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:
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:
If any of the specified element in this queue is null, it will give NullPointerException as
described above.
CreateObjectExample1.java
Output:
Welcome to javaTpoint
By using the new keyword, we can also invoke the constructor (default or parametrized)
of the class.
CreateObjectExample2.java
Welcome to javaTpoint
Note: The method creates a copy of the object not a new object.
Syntax:
CreateObjectExample3.java
Output:
Syntax:
AD
Or
1. ClassName object = (ClassName) Class.forName("fully qualified name of the class
").newInstance();
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
Output:
Syntax:
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:
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,
Syntax:
Syntax:
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. }
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
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.
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.
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.
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.
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. }
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.
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.
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.
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
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.