JAVA UNIT II Final
JAVA UNIT II Final
Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration
of Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing
Private Members of Class, Constructor Methods for Class, Overloaded Constructor Methods,
Nested Classes, Final Class and Methods, Passing Arguments by Value and by Reference,
Keyword this. Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded
Constructor Methods, Class Objects as Parameters in Methods, Access Control, Recursive
Methods, Nesting of Methods, Overriding Methods, Attributes Final and Static.
• Classes
• Objects
• Polymorphism
• Inheritance
• Encapsulation
Abstraction
•
• Instance
• Method
• Message Passing
Classes and objects:
Classes and objects are the fundamental components of OOP's. Often there is a confusion
between classes and objects. In this tutorial, we try to tell you the difference between class
and object.
Define Class:
• A class is a blueprint for the object. Before we create an object, we first need to define the
class.
• A class is an entity that determines how an object will behave and what the object will
contain. In other words, it is a blueprint or a set of instruction to build a specific type of
object.
1
Class Members in JAVA: or Components of a Class
1. Variables (States)
2. Methods (Behaviors)
3. Constructor
4. Blocks (Instance/Static Blocks )
5. Inner Classes.
1. Modifiers: A class can be either a public or default access modifier. But the members of class
can be public, private, default, and protected. All these are the access modifiers.
2. Class name: By convention, a class name should begin with a capital letter and subsequent
characters lowercased (for example Student).
2
3. Body: Every class’s body is enclosed in a pair of left and right braces. In the body, a class
can contain the following members.
4.Fields: Fields are data member variables of a class that stores data or value in it. It specifies
the state or properties of the class and its object. It may be a local variable, instance variable,
or static variable.
5.Constructor: A constructor is used to create an object. Every class must be at least one
constructor otherwise, no object can be created of the class.
If you don’t explicitly define a constructor, the compiler automatically adds a default constructor
inside the class. A constructor can be divided into two types, such as default constructor and
user-defined constructor.
6.Method: A method defines an action or behavior of the class that a class’s object can perform.
It has a body within braces. In the body, we write code that performs actions. It may be an
instance method or a static method.
7.Block: A block is mostly used to change the default values of variables. It may be an instance
block or static block.
8. main Method: A class has also the main method that provides the entry point to start the
execution of any program. The main method is static in nature.
3
Class - Dogs
Data members - breed, size, color, age etc.
Methods- eat(), run(), sleep(), name().
4
Example to write main() Method outside class
Object in JAVA:
Object Definitions:
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.
5
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:
Multiple Objects
Create two objects of Main: You can create multiple objects of one class:
6
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used
for better organization of classes (one class has all the attributes and methods, while the
other class holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this example, we
have created two files in the same directory/folder:
• Main.java
• Second.java
Main.java
public class Main {
int x = 5;
}
Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
How to Initialize object in JAVA:
There is three Ways to initialize object
• By reference variable
• By method
• By constructor
7
Object Creation and assigning values through method
class Student{ Output:
String name; //field or data member or instance
Ramboo
variable
int rollNo;//field or data member or instance variable 21
void methodforInti(String s, int r)
{
name = s;
rollNo = r;
}
public static void main(String args[]){
Student obj1=new Student();
obj1.methodforInti("Ramboo",21);
System.out.println(obj1.name+"'s Roll No: "+obj1.rollNo);
}
}
8
public Class Cloud //OUTPUT
{
//OBJ2= RED, OBJ3= RED
String color;
public static void main(String[] args) //Color= RED
{
Cloud obj1 = new Cloud(); Obj2 and Obj 3 are
obj1.color = "RED"; assigned to Obj1 in this
example
Cloud obj2, obj3;
obj2 = obj1; //Assign obj1 to obj2
obj3 = obj2; //Assign obj2 to obj3
System.out.println("OBJ2= " + obj2.color + ", OBJ3= " + obj3.color);
obj2=null; obj3=null;
System.out.print("Color= " + obj1.color);
}
}
Polymorphism
• Existing in many forms is known as
polymorphism.
• For example: to convince the customer
differently, to draw something, for example,
shape, triangle, rectangle, etc.
• In Java, we use method overloading and
method overriding to achieve polymorphism.
• for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
• Hiding internal details and showing
functionality is known as abstraction.
• In Java, we use abstract class and interface
to achieve abstraction.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
9
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private her
A default access modifier in Java has no specific keyword. Whenever the access modifier is not
specified, then it is assumed to be the default. The entities like classes, methods, and variables
can have a default access.
10
A default class is accessible inside the package but it is not accessible from outside the
package.
A class or a method or a data field specified as ‘public’ is accessible from any class or package
in the Java program. The public entity is accessible within the package as well as outside the
package.
class A Output:
{
public void display() Hello World
{
System.out.println("Hello World!!");
}
}
class Main
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}}
11
Private Access Modifier :
The ‘private’ access modifier is the one that has the lowest accessibility level. The methods and
fields that are declared as private are not accessible outside the class. They are accessible
only within the class which has these private entities as its members.
Note that the private entities are not even visible to the subclasses of the class. A private
access modifier ensures encapsulation in Java.
}
public class Main{
public static void main(String args[]){
TestClass obj=new TestClass();
System.out.println(obj.num);//try to access private data member - Compile Time Error
obj.printMessage();//Accessing private method - Compile Time Error
}
}
Output:
TestClass.java:7: error: class Main is public, should be declared in a file named Main.java
public class Main{
^
TestClass.java:10: error: num has private access in TestClass
System.out.println(obj.num);//try to access private data member - Compile Time Error
^
TestClass.java:11: error: printMessage() has private access in TestClass
obj.printMessage();//Accessing private method - Compile Time Error
^
3 errors
12
Protected Access Modifier
When methods and data members are declared protected, we can access them within the
same package as well as from subclasses. For example,
Constructors in JAVA:
A constructor is a special kind of method that determines how an object is initialized when it’s
created.
Syntax
Following is the syntax of a constructor –
class ClassName
{
ClassName()
{
}
}
13
Types of Java constructors
1. Default constructor (no-arg constructor)
2. Parameterized constructor.
In this example, we are creating the no-arg constructor in the Sample class. It will be invoked
at the time of object creation.
14
Example of Parameterized Constructor
The process of defining more than one constructor with different parameters in a class is
known as constructor overloading. Parameters can differ in number, type or order.
15
Example:
class RectangleArea class Main {
{ String language;
private int length; // constructor with no parameter
private int breadth; Main() {
this.language = "Java";
RectangleArea(int l, int b) { }
length = l; // constructor with a single parameter
breadth = b; Main(String language) {
} this.language = language;
RectangleArea(int side) { }
length = side; public void getName() {
breadth = side; System.out.println("Programming
} Langauage: " + this.language);
}
public int getArea() { public static void main(String[] args) {
return length * breadth; // call constructor with no parameter
} Main obj1 = new Main();
public static void main(String[] args) { // call constructor with a single
RectangleArea rect = new RectangleArea(4, 5); parameter
RectangleArea sq = new RectangleArea(5); Main obj2 = new Main("Python");
System.out.println(rect.getArea()); obj1.getName();
System.out.println(sq.getArea()); obj2.getName();
} }
} }
Output: Output:
20 Programming language: Java
25 Programming language: Python
class OuterClass
{
int x = 10;
class InnerClass {
int y = 5;
}
}
16
Advantage of Java inner classes:
There are basically three advantages of inner classes in java. They are as follows:
• Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
• Nested classes are used to develop more readable and maintainable code because it
logically groups classes and interfaces in one place only.
• Code Optimization: It requires less code to write.
• If the nested class i.e the class defined within another class, has static modifier applied in
it, then it is called as static nested class.
• JAVA static nested classes are declared by using the “static” keyword before class at the
time of class definition.
17
Inner Class or Member Inner Class:
The most important type of nested class is the inner class. An inner class is a non-static nested
class. It has access to all of the variables and methods of its outer class and may refer to them
directly in the same way that other non-static members of the outer class do.
• In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.
• A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.
18
class OuterclassTest { class Outer
// instance method of the outer class {
void my_Method() { int count;
int num = 21; public void display()
class MethodInnerClass { // class inside method {
public void print() { for(int i=0;i<5;i++)
System.out.println("This is method inner class {
"+num); class Inner //Inner class defined inside
} for loop
} // end of inner class {
MethodInnerClass inner = new public void show()
MethodInnerClass(); {
inner.print(); System.out.println("Inside inner
} "+(count++));
public static void main(String args[]) { }
OuterclassTest outer = new OuterclassTest(); }
outer.my_Method(); Inner in=new Inner();
}} in.show();
Output: } }}
This is method inner class 21 class Test
{
Output: public static void main(String[] args)
{
Inside inner 0
Inside inner 1
Outer ot=new Outer();
Inside inner 2 ot.display();
Inside inner 3 }}
Inside inner 4
Syntax:
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
19
abstract class AnonymousInner Output:
{
This is an example of
public abstract void message();
anonymous inner class
}
public class OuterClass
{
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void message() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.message();
}}
Type Description
Member Inner Class A class created within class and outside method.
The final keyword in java is used to restrict the user. It is used to make a variable as a
constant, Restrict method overriding, Restrict inheritance. It is used at variable level,
method level and class level. In java language final keyword can be used in following way.
20
Examples of JAVA final variable
public class Circle Output:
{
3.14
public static final double PI=3.14159;
public static void main(String[] args)
{
System.out.println(PI);
}}
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.
22
Java Pass By Value or Call by value
23
What is this Keyword in Java?
• this keyword in Java is a reference variable that refers to the current object of a method
or a constructor.
• The main purpose of using this keyword in Java is to remove the confusion between
class attributes and parameters that have same names.
Value of x=8
Methods:
Method:
Why use methods? To reuse code: define the code once, and use it many times.
• User-defined Methods: We can create our own method based on our requirements.
• Standard Library Methods: These are built-in methods in Java that are available to use.
24
Declaring a Java Method
returnType methodName() {
// method body
Here,
returnType - It specifies what type of value a method returns For example if a method has
an int return type then it returns an integer value.
If the method does not return a value, its return type is void.
method body - It includes the programming statements that are used to perform some tasks.
The method body is enclosed inside the curly braces { }.
Example:
int addNumbers()
{ return sum ;
25
class Main {
// create a method
public static int square(int num) {
return num * num; // return statement
}
public static void main(String[] args) {
int result;
// store returned value to result
result = square(10); // call the method
System.out.println("Squared value of 10 is: " +
result);
}}
Output:
Square value of 10 is 100
These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar)
For example,
• print() is a method of java.io.PrintStream. The print("...") method prints the string inside
quotation marks.
• sqrt() is a method of Math class. It returns the square root of a number.
26
What is Method Overloading
In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different.
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Different ways to overload the method
In this example, we have created two methods, first addition() method performs addition of
two numbers and second addition() method performs addition of three numbers.
27
Method Overloading: changing data type of arguments.
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
28
class Add
{
int a;
int b;
Add(int x,int y)// parametrized constructor
{
a=x;
b=y;
}
void sum(Add A1) // object 'A1' passed as parameter in function 'sum'
{
int sum1=A1.a+A1.b;
System.out.println("Sum of a and b :"+sum1);
}
}
public class classExAdd
{
public static void main(String arg[])
{
Add A=new Add(5,8); /* Calls the parametrized constructor with set of parameters*/
A.sum(A);
}
}
Output:
Sum of a and b is 13
Add(Add A)
{
a=A.a;
b=A.b;
}
Add(int x,int y)
{
a=x;
b=y;
}
29
void sum()
{
int sum1=a+b;
System.out.println("Sum of a and b :"+sum1);
}}
class ExAddcons
{
public static void main(String arg[])
{
Add A=new Add(15,8);
Add A1=new Add(A);
A1.sum();
}
}
Output:
Sum of a and b is 23
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.
class Vehicle
{ void run(){System.out.println("Vehicle is running");} //defining a method
It is also known as static polymorphism, early It is also known as dynamic polymorphism, late
binding, or overloading binding, or overriding
The program’s execution is fast as it involves the The program’s execution is slow as it does not
use of a compiler involve a compiler
31
Factorial Number
public class RecursionExample3 { factorial(5)
static int factorial(int n){ factorial(4)
if (n == 1) factorial(3)
return 1;
factorial(2)
else
factorial(1)
return(n * factorial(n-1));
return 1
}
return 2*1 = 2
public static void main(String[] args) {
return 3*2 = 6
System.out.println("Factorial of 5 is: "+factorial(5));
} return 4*6 = 24
Fibonacci Series
32
Method within Method or Nesting of Methods in JAVA:
The final keyword in java is used to restrict the user. It is used to make a variable as a constant,
restrict method overriding, Restrict inheritance. It is used at variable level, method level and
class level.
In java language final keyword can be used in following way.
final method
• When a method is declared with final keyword, it is called a final method.
• A final method cannot be overridden. Which means even though a sub class can
call the final method of parent class without any issues but it cannot override it.
34
Java final Class
A class declaration with word-final is known as the final class. Final Class in Java can not be
inherited & can not be extended by other classes. A final class can extend other classes; It can
be a subclass but not a superclass.
35
Static Variable in JAVA:
If we declare any instance variable with a static modifier, it is known as static variable in java.
A static variable is also known as class variable in java. It stores the value for a variable in a
common memory location.
36