Java_Unit-2
Java_Unit-2
Sudheer Benarji
Assistant Professor
Email: [email protected]
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 1
Constructors
Constructors
▪ It can be tedious to initialize all of the variables in a class each time an instance is
created.
▪ Even when you add convenience functions like setDim( ), it would be simpler and more
concise to have all of the setup done at the time the object is first created.
▪ Because the requirement for initialization is so common, Java allows objects to
initialize themselves when they are created.
▪ This automatic initialization is performed through the use of a constructor.
▪ A constructor initializes an object immediately upon creation.
▪ It has the same name as the class in which it resides and is syntactically similar to a
method.
▪ Once defined, the constructor is automatically called immediately after the object
is created, before the new operator completes.
▪ Constructors look a little strange because they have no return type, not even void.
▪ This is because the implicit return type of a class’ constructor is the class type
itself.
▪ It is the constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 2
Constructors
Lets look at setDim( ) to initialize dimensions of each box using a parameterized method: As you can see, the setDim( ) method is used to
set the dimensions of each box. For example,
when mybox1.setDim(10, 20, 15); is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d.
// get volume
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 3
of second box
Constructors
▪ You can rework the Box example so that the dimensions of a box are automatically initialized when an object is
constructed.
▪ To do so, replace setDim( ) with a constructor. Let’s begin by defining a simple constructor that simply sets the
dimensions of each box to the same values. This version is shown here:
/* Here, Box uses a constructor to initialize class BoxDemo6 { When this program is
the dimensions of a box. public static void main(String args[]) { run, it generates the
*/ // declare, allocate, and initialize
Box objects
following results:
class Box {
double width; Box mybox1 = new Box(); Constructing Box
double height; Box mybox2 = new Box(); Constructing Box
double depth; double vol; Volume is 1000.0
// This is the constructor for Box. // get volume of first box Volume is 1000.0
Box() { vol = mybox1.volume();
System.out.println("Constructing Box"); System.out.println("Volume is " + vol);
width = 10; // get volume of second box
height = 10; vol = mybox2.volume();
depth = 10; System.out.println("Volume is " + vol);
} }
// compute and return volume }
double volume() {
return width * height * depth;
}
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 4
Constructors
▪ As you can see, both mybox1 and mybox2 were initialized by the Box( ) constructor when they were created.
▪ Since the constructor gives all boxes the same dimensions, 10 by 10 by 10, both mybox1 and mybox2 will have
the same volume.
▪ The println( ) statement inside Box( ) is for the sake of illustration only.
▪ Most constructors will not display anything. They will simply initialize an object.
Before moving on, let’s reexamine the new operator. As you know, when you allocate an object, you use the following
general form:
class-var = new classname( );
Now you can understand why the parentheses are needed after the class name.
What is actually happening is that the constructor for the class is being called. Thus, in the line
Box mybox1 = new Box();
new Box( ) is calling the Box( ) constructor.
When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class.
This is why the preceding line of code worked in earlier versions of Box that did not define a constructor.
The default constructor automatically initializes all instance variables to zero.
The default constructor is often sufficient for simple classes, but it usually won’t do for more sophisticated ones.
Once you define your own constructor, the default constructor is no longer used.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 5
Constructors
default constructor:
In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 6
Constructors
parameterized constructor:
While the Box( ) constructor in the preceding example does initialize a Box object, it is not very useful—all boxes have
the same dimensions.
What is needed is a way to construct Box objects of various dimensions.
The easy solution is to add parameters to the constructor.
As you can probably guess, this makes them much more useful.
For example, the following version of Box defines a parameterized constructor that sets the dimensions of a box as
specified by those parameters.
Pay special attention to how Box objects are created.
/* Here, Box uses a parameterized constructor to class BoxDemo7 { The output from this program is
initialize the dimensions of a box.
public static void main(String args[]) { shown here:
*/
// declare, allocate, and initialize Box objects Volume is 3000.0
class Box {
double width; Box mybox1 = new Box(10, 20, 15); Volume is 162.0
double height; Box mybox2 = new Box(3, 6, 9);
double depth; double vol; As you can see, each object is
// This is the constructor for Box. // get volume of first box
Box(double w, double h, double d) { initialized as specified in the
vol = mybox1.volume(); parameters to its constructor.
width = w;
System.out.println("Volume is " + vol);
height = h; For example, in the following line,
depth = d; // get volume of second box Box mybox1 = new Box(10, 20, 15);
} vol = mybox2.volume(); the values 10, 20, and 15 are passed to the
// compute and return volume System.out.println("Volume is " + vol); Box( ) constructor when new creates the
double volume() { } object.
return width * height * depth; Thus, mybox1’s copy of width, height, and
} depth will contain the values 10, 20, and 15,
}
} respectively.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 7
this Keyword
The this Keyword:
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this
keyword. this can be used inside any method to refer to the current object. That is, this is always a reference
to the object on which the method was invoked. You can use this anywhere a reference to an object of the
current class’ type is permitted.
To better understand what this refers to, consider the following version of Box( ):
This version of Box( ) operates exactly like the earlier version. The use of this is redundant, but perfectly
correct. Inside Box( ), this will always refer to the invoking object. While it is redundant in this case, this is
useful in other contexts, one of which is explained in the next section.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 8
this Keyword
Instance Variable Hiding:
▪ As you know, it is illegal in Java to declare two local variables with the same name inside the same
or enclosing scopes.
▪ Interestingly, you can have local variables, including formal parameters to methods, which overlap with
the names of the class’ instance variables.
▪ However, when a local variable has the same name as an instance variable, the local variable hides
the instance variable.
▪ This is why width, height, and depth were not used as the names of the parameters to the Box( )
constructor inside the Box class.
▪ If they had been, then width would have referred to the formal parameter, hiding the instance
variable width.
▪ While it is usually easier to simply use different names, there is another way around this situation.
▪ Because this lets you refer directly to the object, you can use it to resolve any name space collisions that
might occur between instance variables and local variables.
▪ For example, here is another version of Box( ), which uses width, height, and depth for parameter names
and then uses this to access the instance variables by the same name:
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 9
Garbage Collection
Garbage Collection:
▪ Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
▪ In some languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
▪ Java takes a different approach; it handles deallocation for you automatically.
▪ The technique that accomplishes this is called garbage collection.
▪ It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed.
▪ There is no explicit need to destroy objects as in C++.
▪ Garbage collection only occurs sporadically (if at all) during the execution of your
program.
▪ It will not occur simply because one or more objects exist that are no longer used.
▪ Furthermore, different Java run-time implementations will take varying approaches to
garbage collection, but for the most part, you should not have to think about it while
writing your programs.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 10
The finalize( ) Method
The finalize( ) Method:
▪ Sometimes an object will need to perform some action when it is destroyed.
▪ For example, if an object is holding some non-Java resource such as a file handle or character font, then you
might want to make sure these resources are freed before an object is destroyed.
▪ To handle such situations, Java provides a mechanism called finalization.
▪ By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed
by the garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method.
The Java run time calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.
The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or
indirectly through other referenced objects.
Right before an asset is freed, the Java run time calls the finalize( ) method on the object.
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.
It is important to understand that finalize( ) is only called just prior to garbage collection. It is not called when an object
goes out-of-scope, for example. This means that you cannot know when—or even if—finalize( ) will be executed.
Therefore, your program should provide other means of releasing system resources, etc., used by the object.
It must not rely on finalize( ) for normal program operation.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 11
Java Garbage Collection
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way
to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
○ It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
○ It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 12
Java Garbage Collection
finalize() method:
1) By nulling a reference:
The finalize() method is invoked each time before the object
1. Employee e=new Employee(); is garbage collected. This method can be used to perform
2. e=null; cleanup processing. This method is defined in Object class as:
3) By anonymous object: The gc() method is used to invoke the garbage collector to
perform cleanup processing. The gc() is found in System
and Runtime classes.
6. new Employee();
public static void gc(){}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 13
Simple Example of garbage collection in java
Output:
public class TestGarbage{
object is garbage collected
System.out.println("object is garbage
collected");
s1=null;
s2=null;
System.gc();
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 14
Overloading Methods
Overloading Methods:
// Demonstrate method overloading. class Overload {
class OverloadDemo { public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
void test() { double result;
System.out.println("No parameters"); // call all versions of test()
} ob.test();
ob.test(10);
// Overload test for one integer parameter. ob.test(10, 20);
void test(int a) { result = ob.test(123.25);
System.out.println("a: " + a); System.out.println("Result of ob.test(123.25): " + result);
} }
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
} This program generates the following output:
No parameters
// overload test for a double parameter
double test(double a) { a: 10
System.out.println("double a: " + a); a and b: 10 20
return a*a;
double a: 123.25
}
} Result of ob.test(123.25): 15190.5625
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 15
Overloading Constructors
Using Objects as Parameters:
// Objects may be passed to methods. class PassOb {
class Test { public static void main(String args[]) {
int a, b; Test ob1 = new Test(100, 22);
Test(int i, int j) { Test ob2 = new Test(100, 22);
a = i; Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
b = j;
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
// return true if o is equal to the invoking object }
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
This program generates the following output:
}
ob1 == ob2: true
}
ob1 == ob3: false
As you can see, the equals( ) method inside Test compares two objects for equality and returns the result. That is,
it compares the invoking object with the one that it is passed. If they contain the same values, then the method
returns true. Otherwise, it returns false. Notice that the parameter o in equals( ) specifies Test as its type.
Although Test is a class type created by the program, it is used in just the same way as Java’s built-in types.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 16
Overloading Constructors
create copy of one object from another:
// Here, Box allows one object to initialize another. class OverloadCons2 {
class Box { public static void main(String args[]) {
double width;
double height; // create boxes using the various constructors
double depth; Box mybox1 = new Box(10, 20, 15);
// Notice this constructor. It takes an object of type Box. Box mybox2 = new Box();
Box(Box ob) { // pass object to constructor Box mycube = new Box(7);
width = ob.width;
height = ob.height;
Box myclone = new Box(mybox1); // create copy of mybox1
depth = ob.depth; double vol;
} // get volume of first box
// constructor used when all dimensions specified vol = mybox1.volume();
Box(double w, double h, double d) { System.out.println("Volume of mybox1 is " + vol);
width = w;
height = h; // get volume of second box
depth = d; vol = mybox2.volume();
} System.out.println("Volume of mybox2 is " + vol);
// constructor used when no dimensions specified // get volume of cube
Box() {
width = -1; // use -1 to indicate
vol = mycube.volume();
height = -1; // an uninitialized System.out.println("Volume of cube is " + vol);
depth = -1; // box // get volume of clone
} vol = myclone.volume();
// constructor used when cube is created System.out.println("Volume of clone is " + vol);
Box(double len) {
width = height = depth = len; }
} }
// compute and return volume
double volume() {
return width * height * depth;
}
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 17
Overloading Constructors
objects call-by-value & call-by-reference:
call-by-value: call-by-reference:
// Primitive types are passed by value. // Objects are passed by reference.
class Test { class Test {
void meth(int i, int j) { int a, b;
i *= 2; Test(int i, int j) {
a = i;
j /= 2;
b = j;
}
}
} // pass an object
void meth(Test o) {
class CallByValue { o.a *= 2;
public static void main(String args[]) { o.b /= 2;
Test ob = new Test(); }
int a = 15, b = 20; }
System.out.println("a and b before call: " +a + " " + b); class CallByRef {
ob.meth(a, b); public static void main(String args[]) {
System.out.println("a and b after call: " +a + " " + b); Test ob = new Test(15, 20);
} System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
} ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
The output from this program is shown here: }
a and b before call: 15 20 }
This program generates the following output:
a and b after call: 15 20
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 18
Access Control
▪ Encapsulation provides another important attribute: access control.
▪ Through encapsulation, you can control what parts of a program can access
the members of a class.
▪ By controlling access, you can prevent misuse.
▪ For example, allowing access to data only through a well - defined set of
methods, you can prevent the misuse of that data.
▪ Thus, when correctly implemented, a class creates a “black box” which may be
used, but the inner workings of which are not open to tampering.
▪ However, the classes that were presented earlier do not completely meet this goal.
▪ For example, consider the Stack class. While it is true that the methods
push( ) and pop( ) do provide a controlled interface to the stack, this
interface is not enforced.
▪ That is, it is possible for another part of the program to bypass these
methods and access the stack directly.
▪ Of course, in the wrong hands, this could lead to trouble.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 19
Access Control
▪ Java’s access specifiers are public, private, and protected.
▪ Java also defines a default access level.
▪ protected applies only when inheritance is involved.
▪ The other access specifiers are described next.
▪ Let’s begin by defining public and private.
▪ When a member of a class is modified by the public specifier, then that
member can be accessed by any other code.
▪ When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
▪ Now you can understand why main( ) has always been preceded by the public
specifier. It is called by code that is outside the program—that is, by the Java run-
time system.
▪ When no access specifier is used, then by default the member of a
class is public within its own package, but cannot be accessed outside of
its package.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 20
Access Control
▪ An access specifier precedes the rest of a member’s type specification. That is, it must begin a member’s declaration statement. Here
is an example:
public int i;
private double j; As you can see, inside the
private int myMethod(int a, char b) { // ... TestAccessSpecify class,
▪ To understand the effects of public and private access, consider the following program:
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 21
Access Control
▪ To see how access control can be applied to a more practical example, consider the following improved version of the Stack class:
// This class defines an integer stack that can hold 10 values. class TestStack {
class Stack { public static void main(String args[]) {
/* Now, both stck and tos are private. This means that they cannot be accidentally Stack mystack1 = new Stack();
or maliciously altered in a way that would be harmful to the stack. */ Stack mystack2 = new Stack();
private int stck[] = new int[10]; // push some numbers onto the stack
private int tos; for(int i=0; i<10; i++) mystack1.push(i);
// Initialize top-of-stack for(int i=10; i<20; i++) mystack2.push(i);
Stack() { // pop those numbers off the stack
tos = -1; System.out.println("Stack in mystack1:");
} for(int i=0; i<10; i++)
// Push an item onto the stack System.out.println(mystack1.pop());
void push(int item) { System.out.println("Stack in mystack2:");
if(tos==9) for(int i=0; i<10; i++)
System.out.println("Stack is full."); System.out.println(mystack2.pop());
else // these statements are not legal
stck[++tos] = item; // mystack1.tos = -2;
} // mystack2.stck[3] = 100;
// Pop an item from the stack }
int pop() { }
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 22
Static members
What is the Use of static Keyword in Java
The main use of the static keyword in java is used for memory management in
java.
Whenever we place a static keyword before the initialization of a particular class’s
methods or variables, these static methods and variables belong to the
class instead of their instances or objects.
In Java, static members are those which belongs to the class and
you can access these members without instantiating the class.
The static keyword can be used like
▪ static variables(or fields),
▪ static methods, ,
▪ static classes (inner/nested),
▪ static blocks.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 23
Static members
static variables(or fields):
You can create a static field by using the keyword static.
The static fields have the same value in all the instances of the class.
These are created and initialized when the class is loaded for the first time.
Just like static methods you can access static fields using the class name (without instantiation).
Static Variable in Java
The static variables are those variables that are common to all the instances of the class.
Only a single copy of the static variable is created and shared among all the instances
of the class.
Because it is a class-level variable, memory allocation of such variables only happens once when the
class is loaded in the memory.
If an object modifies the value of a static variable, the change is reflected across all
class Pen {
objects
String penType; // Type of pen whether gel or another
public class MyClass {
String color; // Color of the pen
public static int data = 20; int length; // Length of the pen
public static void main(String args[]){ static String companyName; // static variable
}
System.out.println(MyClass.data);
}
} Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 24
Static members
Storage Area of Static Variable in Java :
The static variables and methods are stored in the heap memory. In fact all static methods
are stored in the Heap memory.
Before the Java 8 version, static variables of the class were stored in the separate section of
the non-heap memory named as Method Area created by the Java Virtual Machine after the
class compilation. Method area section was used to store static variables of the class,
metadata of the class, etc. Whereas, non-static methods and variables were stored in the
heap memory.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 25
Static members
How to Declare a Static Variable in Java
▪ Static variables are declared through the use of static keyword.
▪ The static keyword indicates to the JVM (Java Virtual Machine) that this variable should be
loaded with the class during the compilation of the program.
▪ If we don’t initialize the static variable the default value of the static variable data type will be
automatically assigned to the static variable in java. For example, the default value of integers
is zero, objects is null and so on.
Declaration Examples Example:
Output:
public class Scaler {
// Valid declarations false
//Creating two static members
static int number = 2; 0
static boolean check;
10
// In this case, 0 is automatically static int number;
assigned to number. static int answer = 10;
static int number; public static void main(String[] args) {
System.out.println(Scaler.check); // Default
// Invalid declaration. S should be
value is false.
small
System.out.println(Scaler.number); // Default value is 0.
Static int number = 2; System.out.println(Scaler.answer); // Assigned value is printed.
Explanation: }}
▪ If we don’t assign an initial value to any static variable the default value is automatically initialized to
that particular variable.
▪ In the above example, there are static variables one of boolean type and the second is an integer type.
▪ We didn’t initialize these variables so whenever we try to access these variables we will get the
default values of these variables: false for boolean type variable and the 0 for integer. These are the
default values forDepartment
these data types.Science & Engineering, VNRVJIET, Hyderabad
of Computer March 06, 2023 26
Static members
Declaration Scope of the Static Variables in Java
▪ We cannot declare static variables in the main() method or any kind of
method of the class. The static variables must be declared as a class
member in the class.
▪ Because during compilation time JVM binds static variables to the class level
that means they have to be declared as class members.
Example: Explanation:
class ABC { ● The static variables in java can be declared
static int number; // Valid declaration like class members of the class like static int
void hello() { number, is the valid declaration of the static
static int number1; // Invalid variable but static variables cannot be
declaration declared inside any method scope.
} ● If we try to declare static variables inside any
public static void main(String[] args) method, the compiler will show a syntax error.
{ ● In the beside example if we try to declare a
static String name; // Illegal static variable in the main() method the
modifier
compiler will show an illegal modifier syntax
}
error.
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 27
Static members
Initialization of Static Final Variables in Java
The static variables are also used as constants with the final keyword in Java. Constants must be initialized and
any kind of update is not allowed on them. Let’s understand this with an example.
● Variables declared with static and final keywords must be initialized with a value.
● Final variables cannot be modified as shown below.
class Scaler { ● In the example, if we don’t initialize the
// Creating static constant variable
static variables compiler will show an error
static final int a = 23;
during compilation time.
// Error as static final variables must be initialized. ● In the above program final static variable b
static final int b; is not initialized and hence it will throw an
compile-time error.
public static void main(String[] args) {
System.out.print(a); // 23 will be printed ● The final keyword restricts any changes in
the variable so any kind of increment,
// Error as final variables cannot be modified. decrement, or any other change will violate
a++; this restriction and that’s why the compiler
}
} will show an error in the above case “a++”
line is not a valid statement.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 28
Static members
Accessibility of the Static Variables in Java
Static variables can be accessed by calling the class name of the class. There is no need to create an instance of the
class for accessing the static variables because static variables are the class variables and are shared among all the class
instances.
● The static variables can be accessed in all types of methods: static or non-static.
● We cannot access non-static variables in static methods because non-static variables can only
be accessed by creating an instance of the class.
● However, static methods can be called without creating an instance of the class.
● This leads to reference error for the non-static variable because non-static variables can be accessed only
through an instance of the class that’s why static methods cannot access non-static variables.
● Another way of understanding this: If we have not created any instance of a class and call the static method
public which contains
class Scaler { a non-static reference, which object should the non-static member point to?
Explanation:
int number;
static void check() { ● In the example, a non-static variable named number is called in two
// Error as non-static number is accessed in a methods: one is a static method check() and the other is a non-static
static method method i.e check1().
System.out.println(number); ● When the non-static variable is called inside check(), Java compiler will
} show a reference error because:
void check1() { ○ We can only access the non-static variable only after creating an
System.out.println(number); // Valid accessing instance of the class.
} ○ But static methods can be called without creating an instance of the
} class,
○ That’s why during accessing the non-static variable in the
static method compiler will show reference error.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 29
Static members
Syntax for Accessing:
// Method 1
● Classname: Name of the class containing
// Print the static variable VariableName from class ClassName.
the static variable.
System.out.println(ClassName.VariableName);
● (.) dot operator: Operator used to access
// Method 2 static variables.
// We can access static variables using objects as well ● Variablename: Name of static variable
that needs to be called
// ob is an object of ClassName class
// This throws a warning that can be ignored
System.out.println(ob.VariableName);
Explanation:
public class Main {
static int ans = 10; ● In the example, the static variable named ans is
public static void main(String[] args) { accessed in two ways. One way is without
// Method 1 creating an instance of the class using the class
System.out.println(Main.ans); reference only and the second way is using the
// Method 2 instance of the class.
Main ob = new Main();
● While accessing the static variable in java using the
System.out.print(ob.ans);
}
instance of the class, the compiler will show a
} warning: The static field Main.ans should be accessed
in a static way.
● This is because there is no need to create an instance
of accessing the static members of the class.
March 06, 2023 30
Department of Computer Science & Engineering, VNRVJIET, Hyderabad
Static members
Class containing static members and non-static members:
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 31
Static members
● In the above program, static variable assign() is called by every new instance of the class
and it inserts the name for every new instance and increments the count_clicks variable.
● Since a static variable is shared among all the instances, any changes done due to any
instance automatically update its original state.
● In the above program, we increment static members three times. Hence the output is 3.
This value is same across all instances, which means changes done by any one instance is
reflected across all instances.
● Whenever we create an instance of the class, a separate copy of all the class methods and
variables except static members is created for all respective instances of the class in the
heap memory.
● In the above example the method name as insert() is called by the three instances of the
class and each time insert() method is called the value of count_clicks is increment by
one.
● Since count_clicks is a static variable, it is shared among all the instances of the class so
any changes on this variable are reflected among all the instances of the class.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 32
Static members
Static Methods:
▪ The static method belongs to the class rather than the object of the class.
▪ These are designed to be shared among all the instances of the same class
and they are accessed by the class name of the particular class.
▪ A static keyword is used for declaring the static method in java.
The return_type of the static method can be int, float etc any user-defined datatype.
Note: if we want to make any method to be static, we have to use a keyword i.e static before the declaration of
the method in the class. Let's understand how to declare a static method in java.
The print() method of the class StaticMethodDem is of static type and we don't require an instance of the class for
accessing it. Let's understand how to call static methods.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 34
Static members
Example of How to Call Static Methods?
We can call the static methods with the help of the class name because they belong to the class itself and they have no
relation with the instances of the class.
Syntax:
ClassName.methodName()
The classname is the name of the class followed by the name of the static method.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 35
Static members
Calling non-Static Method from static context: This will give error
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 36
Static members
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 37
Static members
Difference Between Static Method and Static Members in Java
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 38
Static members
public class OverRideStaticMethodExample2
// static method
{
Why can’t we override static
public static void sum(int a, int b) methods in Java?
{
int c=a+b;
System.out.println("The
sum is: "+c);
//main method
OverRideStaticMethodExample2.sum(12, 90);
} Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 39
Static members
static classes (inner/nested):
▪ You cannot use the static keyword with a class unless it is an
inner class.
▪ A static inner class is a nested class which is a static member of the outer class.
▪ It can be accessed without instantiating the outer class, using other static members.
▪ Just like static members, a static nested class does not have access to the instance
variables and methods of the outer class.
Instantiating a static nested class is a bit different from instantiating an
inner class. The following program shows how to use a static nested class.
Syntax public class Outer {
static class Nested_Demo {
class MyOuter {
public void my_method() {
static class Nested_Demo { 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();
}
}
//O/P: This is my nested class
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 40
Static members
static classes (inner/nested):
▪ Static class in Java is a nested class and it doesn't need the reference of the outer class. Static
class can access only the static members of its outer class.
● Nested class-
a. Nested class can be static or non-static.
b. The non-static nested class is known as an inner class.
c. An instance of a static nested class can be created without the instance of the outer class.
d. The static member of the outer class can be accessed only by the static nested class.
e. The nested static class can access the static variables.
f. Static nested classes do not have access to other members of the enclosing class which means it has
no access to the instance variables (non-static variables) which are declared in the outer class.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 42
Static members
static classes (inner/nested):
Why We use Static Class in Java?
In Java, the static keyword helps in efficient memory management. We can access the static members without creating an
instance of a class. We can access them simply by using their class name. It is also a way of grouping classes together. Also,
an instance of a static nested class can be created without the instance of the outer class.
Example:
class Outer { Explanation:
// static member of the outer class ● We have declared Outer and Nested classes. In the outer
private static char grade = 'A'; class, we have created a static member which can be
// Static class accessed by the static class.
static class Nested { ● As we know, static members can be accessed by the static
//non-static method class only, so in the main() method, we have created an
public void fun() { instance of the nested class without the instance of the outer
/* nested class can access the
class as our nested class is static.
static members of the outer class */
System.out.println("Grade: ")+grade;
} Difference Between Static and Non-Static
}
public static void main(String args[]) {
Nested Class
/*creating an object of nested */ ● Static nested class can access the static members of
Outer.Nested obj = new Outer.Nested(); the outer class and not the non-static members,
/* class without creating an object whereas non-static nested class,i.e, the inner class
of the outer class*/ can access the static as well as the non-static
obj.fun(); members of the outer class.
} ● We can create an instance of the static nested class without
}
creating an instance of the outer class.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 43
Static members
static classes (inner/nested):
Conclusion
● Static class in Java is a nested class and it doesn't need the reference of the outer class.
● Static class can access only the static members of its outer class.
● Static class cannot access the non-static member of the outer classes.
● Inner classes can access the static and the non-static members of the outer class.
● We can create an instance of the static nested class without creating an instance of the outer
class.
● The static keyword helps in memory management.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 44
Static members
static classes (inner/nested): Example Program
class Animal{ class StaticClassDemo {
public static void main(String[] args) {
// NON-STATIC NESTED CLASS : - inner class
class Reptile { // object creation of the outer class
public void displayInfo() { Animal animal = new Animal();
System.out.println("I am a reptile.");
} // object creation of the non-static class
} Animal.Reptile reptile = animal.new Reptile();
reptile.displayInfo();
// STATIC NESTED CLASS: - static class
static class Mammal { // object creation of the static nested class
public void displayInfo() { Animal.Mammal mammal = new Animal.Mammal();
System.out.println("I am a mammal.displayInfo();
mammal."); }
} }
}
OUTPUT:
} I am a reptile.
I am a mammal.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 45
Static members
static classes (inner/nested):Example: Accessing Non-static members
class Animal{ class AccessNonStaticMembers {
public static void main(String[] args) {
//Static class
static class Mammal { Animal animal = new Animal();
public void displayInfo() {
System.out.println("I am a mammal."); //creating an object of non-static class
} Animal.Reptile reptile = animal.new Reptile();
} //Accesessing Method of non-static class
//Non-Static class reptile.displayInfo();
class Reptile {
public void displayInfo() { //creating an object of static class
Animal.Mammal mammal = new Animal.Mammal();
System.out.println("I am a reptile.");
//Accesessing Method of static class
} mammal.displayInfo();
} //Accesessing Non-static Method
//Non-Static method mammal.eat();
public void eat() { }
System.out.println("I eat food."); }
}
} OUTPUT:
AccessNonStaticMembers.java:27: error: cannot find
symbol mammal.eat();
We Get Error because: It is because mammal is an ^
object of a static class and we cannot access non- symbol: method eat()
location: variable mammal of type Mammal
static methods from static classes.
1 error
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 46
Static members
static classes (inner/nested):Static Top-level Class
static class Animal {
public static void displayInfo() { Output
System.out.println("I am an animal");
} StaticTopLevelClass.java:1: error: modifier static not
} allowed here
static class Animal {
class StaticTopLevelClass { ^
public static void main(String[] args) { 1 error
Animal.displayInfo();
} compiler exit status 1
We Get Error because: In the above example, we have tried to create a static class Animal.
Since Java doesn’t allow static top-level class, we will get an error.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 47
Static members
Static Blocks:
These are a block of codes with a static keyword. In general, these are used to initialize the
static members.
JVM executes static blocks before the main method at the time of class loading.
Example:
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}
Output:
Hello this is a static block
This is main method
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 48
Static members
Static Blocks:
Introduction to Static Block in Java
▪ Suppose there are some fields in your code, which are needed to be initialized and executed
at the very beginning of the code only once, and you do not want to initialize them every
time.
▪ In that case, we can use a static block in java, which can contain those fields and will
execute them only once at the very beginning when the class is loaded into the memory.
▪ Having learned the main purpose of the static block, now let us formally define what is a
static block in java and its deep significance in our code.
▪ Whenever there is a block that is associated with the static keyword, we refer to that block
as a static block (also called static clause) in java.
▪ The set of codes inside a static block can run only once when the class is loaded into the
memory, by loading of class into memory we mean that, when the Java ClassLoader which is
a part of Java Runtime Environment dynamically loads the Java classes into the Java Virtual
Machine (JVM).
▪ We can say static block can be used for static initialization of a class, this is because it is an
option for initializing or setting up the class during run-time and also the code inside the
static block is executed only once: the first time when the class is loaded into memory. So a
static block is also known as static initialization block.
▪ A static block is executed before the main method during the classloading.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 49
Static members
Static Blocks:
Let us see an example of how to declare a static block in Java.
// Java program to demonstrate static block
public class StaticBlockDemo { Explanation:
static {
//static block ● So in the code, we have created a public class Main,
System.out.println("Hi, I'm a Static Block!"); and inside it we have created a static block.
}
● The static block is automatically executed during the
public static void main(String[] args) { loading of class, At first, the class is loaded into the
//main method memory, that is, JVM loads the dot class file (in byte
System.out.println("Hi, I'm a Main Method!"); code) into the memory.
}
● During the dot class file loading into memory, the
} static block is been executed and it will print its
content.
Output
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 50
Static members
Static Blocks: Calling of Static Block in Java
Now, let us discuss how we can call the static block in java. There is no specific way to call a static block in java, as it is
executed automatically when the class is loaded in the memory.
To clarify the above point, let us take an example to see how the static block in java is called automatically.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 52
Static members
Static Blocks: Static blocks can also be executed before constructors.
Let us see another example of how the static block will execute if the code contains constructors.
/// Java program to demonstrate the execution of Explanation
// Static block before constructors in java
// Class 1 ● In the code, we have a public class MyClass
// Helper class and another class Helper.
class Helper {
● When the code is been executed we can see
// Static blocks
static{ the static block content is printed before
System.out.println("Hi, I'm a Static Block!"); the constructor of the Helper class content.
}
// Constructor of the class
● By this, we got a clear idea that static
Helper(){ blocks can also be executed before
System.out.println("Hi, I'm a Constructor!"); constructors.
}
}
● We have also noticed although we have two
// Class 2 objects, the static block is executed only
// public class once.
public class MyClass{
// Main method
● This is because the static block is executed
public static void main(String args[]) by default during the loading of the class.
{
// Although we have two objects, static
block is
// executed only once.
Helper t1 =Output:
new Helper();
Helper t2 =Hi,
newI'm
Helper();
a Static Block!
} Hi, I'm a Constructor!
} Hi, I'm a Constructor!
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 53
Static members
Static Blocks: How Many Times does a Dot Class File Loaded into
Memory?
A dot class file is loaded into the memory only one time during runtime. So, the static block will be executed only one time
during the loading of the dot class file into the memory. Although the instance block’s execution depends upon the object
creation, that is the number of times the object is created the instance block will be executed that number of times. You
might be thinking about what is an instance block, so let's discuss it in a short overview.
instance block : Instance Initializer block is used to initialize the instance variable or data member. Every time an object of
the class is created, it runs.
If we create 5 objects, the instance blocks will be executed 5 times but the execution of the static block depends upon the
class loading. Since the class is loaded only one time, the static block will be executed only one time.
Let us take an example program to understand this concept better.
public class MyClass { Explanation :
// Instance block ● So in the above code, we have a public class
{
System.out.println("Hi, I'm a Instance Block!"); MyClass which contains an instance block, static
} block, and a main method.
// Static block ● When the program is been executed the static
static { Output : block's content is printed at first and only one time
System.out.println("Hi, I'm a Static Block!"); Hi, I'm a Static Block!
}
during the loading of the class into the memory.
Hi, I'm a Instance Block!
// main method ● AFter that, the instance block's content is printed 5
Hi, I'm a Instance Block!
public static void main(String args[]) { Hi, I'm a Instance Block! times as the object is called 5 times.
MyClass obj1 = new MyClass(); Hi, I'm a Instance Block! ● Hence, we can say the static block is executed only
MyClass obj2 = new MyClass(); Hi, I'm a Instance Block! once during the dot class file (.class) loading into
MyClass obj3 = new MyClass(); Hi, I'm a main Block!
MyClass obj4 = new MyClass(); the memory, and the instance block will be
MyClass obj5 = new MyClass(); executed as many times as the object is created.
System.out.println("Hi, I'm a main Block!");
}
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 54
Static members
Static Blocks: Order of Execution of Multiple Static Blocks in Java
In a java program, a class can have multiple static initialization blocks that will execute in the same order they appear in the
program, that is, the order for the execution of static block in a class will be from top to bottom.
That is, during the loading of the dot class files, the order of execution of multiple static initialization blocks is executed
automatically in sequence from top to bottom.
Let us take an example program to understand the order of execution of multiple static
blocks.
public class MyClass { Explanation :
// Instance block
{
● In the above code, we have a public class MyClass
System.out.println("Hi, I'm a Instance Block!"); which contains an instance block, multiple static
} blocks, and a main method.
// Static block-1
static { ● When the code is executed and during the loading
System.out.println("Static Block-1!"); of the class file, we can clearly see the contents
}
// Static block-2 inside the multiple static blocks are printed in order
static { like the at first the static block-1 is executed then
System.out.println("Static Block-2!"); Output :
the static block-2 and it goes on in order from top to
} Static Block-1!
// Static block-3 Static Block-2! bottom and then after that, the main block is
static { Static Block-3! executed.
System.out.println("Static Block-3!"); Hi, I'm a Instance Block!
}
● We can also see the content inside the instance
Hi, I'm a main Block!
// main method block is printed only once as the object is created
public static void main(String args[]) { only once. in the end, the main method code is also
MyClass obj1 = new MyClass();
System.out.println("Hi, I'm a main Block!"); executed. Hence, we can say the order of execution
} of multiple static initialization blocks is executed
}
automatically from top to bottom during the dot
class file loading.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 55
Static members
Static Blocks: Can we Execute the Static Block without the Main
Method inside a Class?
In Java Development Kit (JDK) version 1.5 or previous the static block can be executed successfully without the
main() method inside the class, but JDK version after 1.5 will throw an error message if there is a static block
but no main() method inside the class.
The static blocks are essentially executed during the loading of the dot class (.class) file, even before the JVM calls the main
method.
public class StaticBlockWithoutMainMethod {
Explanation :
// Static block ● So in the above code, we have a public
static class StaticBlockWithoutMainMethod which
{ contains only a static block. We can
// Print statement clearly see the code is unable to execute
System.out.print("Static block can be printed
successfully and it throws an error: Main
without main method");
} method not found in class
} StaticBlockWithoutMainMethod demanding
for defining the main method.
● Hence, in JDK version 1.5 or later it
Error: Main method not found in class is not possible to execute a static
StaticBlockWithoutMainMethod, please define the main
method as: block without a main method inside
public static void main(String[] args)
or a JavaFX application class must extend
the class.
javafx.application.Application
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 56
Static members
Static Blocks: Difference between Static Block and Instance Block
in Java
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 57
Nested and Inner Classes
In Java, just like nested Loops, we have Nested Classes, i.e., we can define a class inside another
class.
We can group classes with similar properties under an outer class, so they are together. It
increases the encapsulation and readability of the code. The nested class comes under the
principles of Object-Oriented Programming (OOP).
We can not define normal classes as private. But Java treats the nested class as members of the
outer class, and we can define them as private.
Note: Outer class does not have access to the Inner class if the inner class is private. We use
nested classes to group into different classes and to increase security by limiting the scope of
classes.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 58
Nested and Inner Classes
Types of Nested Classes
A nested class can either be defined as a static type or a non-static type. Types in detail:-
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 59
Nested and Inner Classes
Static Nested Classes
A static class is a class that is created inside a class. A static variable is common to all the instances of that particular class.
Similarly, a static class can access all the instance functions of the outer class.
To do this, we will have to make objects of child classes and refer to them. We can access all the static functions of the outer
class without object creation.
Syntax:
class Parent_Class
Let us see an example of using the static nested class and
{
accessing its method from other functions.
static class Static_Child_Class // parent class
{ class Parent_To_Nested_Static_Class {
// code static String s = "Static";
} // child class
} static class Static_Child_Class {
// child class method
We can create an object of this class like this: void print(String x) {
System.out.println(s + " " + x);
Static_Child_Class obj = new Static_Child_Class(); }
}
public static void main(String args[]) {
Explanation: // child class object
Here, we have created a nested class. The Static_Child_Class obj = new Static_Child_Class();
Parent_To_Nested_Static_Class is the outer class, String y = "Inner Class";
and the Static_Child_Class is the inner class. The obj.print(y);
main() function of the }
Parent_To_Nested_Static_Class access the inner }
class methods with the object.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 60
Nested and Inner Classes
Non-static Nested Classes (Inner Classes)
A non-static nested class or inner class is a class within a class. We do not define it as static so that it can directly use all the
functions and variables of the outer class.
From the inner class, if we want to access any static method of the outer class, we do not need any object; we can call it
directly.
Let us see an example of using the non-Static nested class
1. Member Inner Classes and accessing its method from other functions:-
// parent class
class Parent_To_Nested_Non_Static_Class {
Syntax:
String s = "Non_Static ";
class parent_class {
// child class
class child_class {
class child_class {
// code
void print(String x) {
}
System.out.println(s + " " + x);
}
}
To access the non-static inner class from the static main method or }
any other static method, public static void main(String args[]) {
we have to create objects of the parent_class as well as the child_class. // parent class object
The syntax for these objects: Parent_To_Nested_Non_Static_Class parentObj =
parent_class parentObj = new parent_class(); new Parent_To_Nested_Non_Static_Class();
child_class childObj = parentObj.new child_class(); // child class object using parent class object
Explanation: child_class childObj = parentObj.new child_class();
String y = "Inner Class";
Here, we are creating an object of the parent class and, // calling methods of child class
with the help of it, creating the object of the child class. childObj.print(y);
We are accessing the methods of the child_class }
using the childObj. We had to do this because }
the child_class is non-static, while the main
method is static.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 61
Nested and Inner Classes
Non-static Nested Classes (Inner Classes)
2. Local Inner Classes
A Local Inner class is a class that is defined inside any block, i.e., for block, if block, methods, etc. Similar to local variables,
the scope of the Local Inner Class is restricted to the block where it is defined.
Syntax:
class class_name { Let us see an example of using the Local inner class and
void method_name() { accessing its method:-
// code // parent class
if(conditions) { class Parent_To_LocalInnerClass {
// or any other block like while, for, etc. public static void main(String args[]) {
class localInnerClass { String s = "Local";
void localInnerMethod() { if (s.charAt(0) == 'L') {
// code // child class
} class child_class {
} void print(String x) {
} System.out.println(s + " " + x);
// code }
} }
} // child class object
child_class childObj = new child_class();
String y = "Inner Class";
Explanation: // calling child class method
childObj.print(y);
Here, we are defining a class inside an if block. // child_class is accessible till here only
And we are creating an object of child_class and }
calling it from the same block. The child_class // child_class is not accessible here
}
is only accessible from the if block and can
}
not be called from outside.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 62
Nested and Inner Classes
Non-static Nested Classes (Inner Classes)
3. Anonymous Inner Classes
Anonymous Inner class is an inner class but without a name. Let us see an example of Anonymous inner
It has only a single object. class and accessing its methods:-
It is used to override a method. // abstract Class
It is only accessible in the block where it is defined. abstract class Printer {
We can use an abstract class to define the anonymous innerabstract class. void print(String x);
It has access to all the members of the parent class.
}
It is useful to shorten over code.
Basically, it merges the step of creating an object and defining the // Parent Class
class.
class Parent_To_AnonymousInnerClass {
Syntax: public static void main(String args[]) {
abstractClass obj = new abstractClass() { // Anonymous Inner Class
Printer obj = new Printer() {
void methods() {
void print(String x) {
// code
System.out.println("Anonymous Inner " + x);
}
}
Explanation:
}; };
The Printer object is used to define the
String y = "Class";
anonymous inner class. Then we are calling the
obj.print(y);
print() method of the anonymous inner class }
using the object we just defined. }
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 63
Nested and Inner Classes
Static Nested Classes & Non-static Nested Classes
(Inner Classes)
Conclusion:
● Nested classes are classes inside another class.
● We use Nested Classes to group into different classes and to
increase the security by limiting the scope of classes.
● While compiling a Nested class, multiple .class files are
generated, 1 for each class.
● In Nested classes, the outer class does not have access to the
data and methods of the inner class if the inner class is private.
● We have two types of Nested Classes
○ Static Nested Class
○ Non-Static Nested Class
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 64
Command line arguments
▪ Every program deals with some type of data. This data can be either provided to it by the user
or the programmer.
▪ The user hardly provides a big input to process. Whereas the programmer needs to provide various
different types of data inputs for efficient testing.
▪ Now, this process may end up eating a lot of time on either manually entering inputs or hard coding
data variables.
▪ We need to come up with a solution where we can do efficient testing with minimum effort and time.
The below representation shows the two ways by which we can write our main function in Java.
The argument String[] args or String… args can be broken down as follows.
▪ If we provide inputs following this command the JVM (Java Virtual Machine) wraps all these
inputs together.
▪ It then supplies it to the main function parameter String[] args or String… args.
▪ This process takes place even before our main() is even invoked.
▪ These inputs are called command line arguments. Since these inputs are passed to our
application before its execution, they provide us a way to configure our application with
different parameters.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 66
▪ This helps us in doing efficient testing of our application.
Command line arguments
How to Pass Command Line Arguments In Java?
In order to pass command line arguments in Java, we need to follow the following steps.
1. Write your java program and save it with .java extension in your local system
2. Open your cmd(command prompt) and navigate to the directory where you saved your
program
3. Compile your program using command ‘javac filename.java’. This will convert the .java file
to .class file
4. Write the run command ‘java filename’ and continue the command with all the inputs you
want to give to your code
5. After writing all your inputs, run your command
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 69
Command line arguments
How to Modify Command Line Arguments in Java?
The command line inputs are read as strings by the compiler and stored in an array. We can modify them by using the
reference operator’[]’. The following program shows an example where we read the command line arguments and later
modify them.
Here the input is accessed using the ‘[]’ operator and then we assign a new value to it. This assigned value overwrites the
previous input. Output:
PS C:\MinGW\bin> Java cmdArgs 1 a black 98765 $%^ !@
public class cmdArgs{ The number of command line inputs entered are 6
public static void main(String[] args){ input 1 is 1
System.out.println("The number of commandinput 2line
is a
inputs entered are "+args.length);
input 3 is black
System.out.println("The inputs are as follows");
for(int i=0;i<args.length;i++) input 4 is 98765
input 5 is $%^
System.out.println("input "+(i+1)+" is "+args[i]);
args[1]="this input was changed";
input 6 is !@
System.out.println("Inputs after modification are");
for(int i=0;i<args.length;i++) Inputs after modification are
input 1 is 1
System.out.println("input "+(i+1)+" is "+args[i]);
} input 2 is this input was changes
}
input 3 is black
input 4 is 98765
input 5 is $%^
input 6 is !@
PS C:\MinGW\bin>
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 70
Command line arguments
Important Points about Command Line Inputs in Java
● Command line inputs need to follow the java
● For example: 123 abc @@@ if supplied as java
filename in the command that executes our code
command line arguments they are read as strings
● Almost all data types are read as string but ‘#’, ‘%’,
“123”, “abc” and “@@@”
‘&’ throw an error when entered through the cmd
● Command line inputs can be very useful in testing and
● Command line inputs provide users an alternative
running our applications
way to give inputs
● Initialisation Since these inputs are provided before
● They are easy to access and we can operate on
execution they provide us with a method to initialise
them just like normal arrays
our application with data values of our choice,
● For entering large inputs we have third party
otherwise the same work would have been done by the
libraries like Picocli and Spring Shell
code after it begins its execution For example we need
● These are libraries which are smaller in size and
to test our program for real life conditions with a huge
help us to create java command line applications.
data set. Now entering these inputs one by one will be
They are memory efficient and faster than other
impractical. In these cases if we use command line
libraries
inputs we could just copy our data with the execute
● A Java application can accept any number of
command and provide a huge input easily and quickly
arguments from the command line.There is no
to our program
restriction on the number of inputs entered through
● Application Testing Providing different input values
command line into the main function parameter
helps us to test our programs working. This task can be
● For example: If we are developing an application
difficult if we are made to provide test values manually
that deals with millions of customer’s data at once it
again and again. Command line inputs enable us to
would be challenging every time to test our
reduce our effort and run multiple test values and test
application for such a huge data set. This task can
our program.This enables us to create different real life
be simplified if we use command line inputs with
situations for our code to test and debug. For example:
3rd party libraries
Rather than providing every test input separately we
● Command line inputs are passed as strings to the
could supply complete test data by command line
main function parameterDepartment of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 71
inputs at once and test the program in less time.
Varargs: Variable-Length Arguments
▪ Beginning with JDK 5, Java has included a feature that simplifies the creation of methods
that need to take a variable number of arguments.
▪ This feature is called varargs and it is short for variable-length arguments.
▪ A method that takes a variable number of arguments is called a variable-arity
method, or simply a varargs method.
▪ Situations that require that a variable number of arguments be passed to a method are not
unusual.
▪ For example, a method that opens an Internet connection might take a username, password,
filename, protocol, and so on, but supply defaults if some of this information is not provided.
▪ In this situation, it would be convenient to pass only the arguments to which the defaults did
not apply.
▪ Another example is the printf( ) method that is part of Java’s I/O library.
▪ Prior to JDK 5, variable-length arguments could be handled two ways, neither of which was
particularly pleasing.
▪ First, if the maximum number of arguments was small and known, then you could
create overloaded versions of the method, one for each way the method could be
called.
▪ In cases where the maximum number of potential arguments was larger, or
unknowable, a second approach was used in which the arguments were put into an
array, and then the array was passed to the method.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 72
Varargs: Variable-Length Arguments
This approach is illustrated by the following program:
// Use an array to pass a variable number of arguments to a method.
//This is the old-style approach to variable-length arguments.
class PassArray {
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 73
Varargs: Variable-Length Arguments
The varargs feature offers a simpler, better option.
A variable-length argument is specified by three periods (...).
For example, here is how vaTest( ) is written using a vararg: static void vaTest(int ... v) {
This syntax tells the compiler that vaTest( ) can be called with zero or more
arguments.
As a result, v is implicitly declared as an array of type int[ ].
Thus, inside vaTest( ), v is accessed using the normal array syntax.
Here is the preceding program rewritten using a vararg:
// Demonstrate variable-length arguments.
class VarArgs {
// vaTest() now uses a vararg.
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length + " Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[]){
// Notice how vaTest() can be called with a variable number of arguments.
vaTest(10); // 1 arg
vaTest(1, 2, 3); // 3 args
vaTest(); // no args
}
} //The output from the program is the same as the original version.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 74
Varargs: Variable-Length Arguments
There are two important things to notice about this program.
First, as explained, inside vaTest( ), v is operated on as an array. This is because v is an array.
The ... syntax simply tells the compiler that a variable number of arguments will be used, and
that these arguments will be stored in the array referred to by v.
Second, in main( ), vaTest( ) is called with different numbers of arguments, including no
arguments at all. The arguments are automatically put in an array and passed to v. In the case of
no arguments, the length of the array is zero.
A method can have “normal” parameters along with a variable-length parameter. However, the
variable-length parameter must be the last parameter declared by
the method.
For example, this method declaration is perfectly acceptable: int doIt(int a, int b, double c,
int ... vals) {
In this case, the first three arguments used in a call to doIt( ) are matched to the first three
parameters. Then, any remaining arguments are assumed to belong to vals.
Remember, the varargs parameter must be last. For example, the following declaration is
incorrect:
int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
Here, there is an attempt to declare a regular parameter after the varargs parameter, which is
illegal.
There is one more restriction to be aware of: there must be only one varargs
parameter.
For example, this declaration is also invalid:
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 75
int doIt(int a, int b, double c, int ... vals, double ... morevals ) { // Error!
Varargs: Variable-Length Arguments
Here is a reworked version of the vaTest( ) method that takes a regular argument and a
variable-length argument:
// Use varargs with standard arguments.
class VarArgs2 {
/* Here, msg is a normal parameter and v is a The output from this program is shown
varargs parameter.*/ here:
static void vaTest(String msg, int ... v) { One vararg: 1 Contents: 10
System.out.print(msg + v.length + " Contents:Three
"); varargs: 3 Contents: 1 2 3
for(int x : v) No varargs: 0 Contents:
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[]){
vaTest("One vararg: ", 10);
vaTest("Three varargs: ", 1, 2, 3);
vaTest("No varargs: ");
}
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 76
Varargs: Variable-Length Arguments
Overloading Vararg Methods
You can overload a method that takes a variable-length argument. For example, the following
program overloads vaTest( ) three times:
// Varargs and overloading.
class VarArgs3 { public static void main(String args[]){
static void vaTest(int ... v) { vaTest(1, 2, 3);
System.out.print("vaTest(int ...): " vaTest("Testing: ", 10, 20);
+"Number of args: " + v.length +" vaTest(true, false, false);
Contents: "); }
for(int x : v)
}
System.out.print(x + " ");
System.out.println();
} The output produced by this program is shown here:
static void vaTest(boolean ... v) {
vaTest(int ...): Number of args: 3 Contents: 1 2 3
System.out.print("vaTest(boolean ...) " vaTest(String, int ...): Testing: 2 Contents: 10 20
+"Number of args: " + v.length +" vaTest(boolean ...) Number of args: 3 Contents: true false false
Contents: ");
for(boolean x : v) varargs method can be overloaded.
System.out.print(x + " ");
System.out.println(); First, the types of its vararg parameter can differ. This is the
} case for vaTest(int ...) and vaTest(boolean ...).
static void vaTest(String msg, The second way to overload a varargs method is to add a
normal parameter. This is what was done with
int ... v) { vaTest(String, int ...).
System.out.print("vaTest(String, int ...): "
+msg + v.length +" Contents: ");
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 77
for(int x : v)
Varargs: Variable-Length Arguments
Varargs and Ambiguity
Somewhat unexpected errors can result when overloading a method that takes a variable-length argument.
These errors involve ambiguity because it is possible to create an ambiguous call to an overloaded varargs
method.
For example, consider the following program: Varargs, overloading, and ambiguity.This program contains
an error and will not compile! In this program, the overloading of vaTest( ) is perfectly correct.
class VarArgs4 { However, this program will not compile because of the following
static void vaTest(int ... v) { call:
System.out.print("vaTest(int ...): " vaTest(); // Error: Ambiguous!
+"Number of args: " + v.length +" Contents: ");
Because the vararg parameter can be empty, this call could be
for(int x : v)
System.out.print(x + " "); translated into a call to vaTest(int ...) or vaTest(boolean ...). Both
System.out.println(); are equally valid. Thus, the call is inherently ambiguous.
} Here is another example of ambiguity. The following overloaded
static void vaTest(boolean ... v) { versions of vaTest( ) are inherently ambiguous even though one
System.out.print("vaTest(boolean ...) " takes a normal parameter:
+"Number of args: " + v.length +" Contents: ");
static void vaTest(int ... v) { // ...
for(boolean x : v)
System.out.print(x + " "); static void vaTest(int n, int ... v) { // ...
System.out.println(); Although the parameter lists of vaTest( ) differ, there is no way
} for the compiler to resolve the following call:
public static void main(String args[]){ vaTest(1)
vaTest(1, 2, 3); // OK Does this translate into a call to vaTest(int ...), with one varargs
vaTest(true, false, false); // OK
argument, or into a call to vaTest(int, int ...) with no varargs
vaTest(); // Error: Ambiguous!
} arguments? There is no way for the compiler to answer this
} question. Thus, the situation is ambiguous.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 78
Inheritance
Inheritance is a mechanism wherein one class inherits the property of another.
In inheritance, one class can adopt the methods and behavior of another class.
It is a useful practice if you want to avoid writing the same piece of code repeatedly.
Introduction to Inheritance in Java
▪ Inheritance is an object-oriented programming concept in which one class acquires the properties and behavior
of another class. It represents a parent-child relationship between two classes. This parent-child relationship is
also known as an IS-A relationship.
▪ Let us discuss a real-world example that helps us understand the need and importance of inheritance.
▪ Imagine you have built a standard calculator application in java. Your application does addition, subtraction,
multiplication, division, and square root.
▪ Now, you are asked to build a scientific calculator, which does additional operations like power, logarithms,
trigonometric operations, etc., along with standard operations. So, how would you go about writing this new
scientific calculator application?
▪ Would you write the code for all standard operations, like addition, subtraction, etc., again? No, you have
already written that code. Right? You would want to use it in this new application without writing it all
over again. Using inheritance in this case, you can achieve this objective.
class SuperClass {
void methodSuper() { Explanation:
System.out.println("I am a super class method");
} ● A class Superclass with method
}
methodSuper() and another class
// Inheriting SuperClass to SubClass SubClass with method
class SubClass extends SuperClass { methodSubclass()are written.
void methodSubclass() { ● Inherit the Superclass to SubClass using
System.out.println("I am a sub class method"); the extends keyword.
} ● Create an object for SubClass obj in the
} main method
class Main {
● Since the Superclass is inherited to the
public static void main(String args[]) {
SubClass obj = new SubClass(); SubClass, the methodSuper() of
obj.methodSubclass(); Superclass is now part of the SubClass.
obj.methodSuper(); ● So, SubClass now has two methods,
} methodSuper() and methodSubclass(),
} which can be called using the obj Object
Output:
I am a sub class method
I am a super class method
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 81
Inheritance
Types of Java Inheritances
There are five different types of inheritances that
are possible in Object-Oriented Programming.
1. Single
2. Multilevel
3. Hierarchical
4. Multiple
5. Hybrid
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 82
Inheritance
1. Single Inheritance in Java
This is the simplest form of inheritance, where one class inherits another class.
class Bird { Explanation:
void fly() {
System.out.println("I am a Bird"); ● Bird Class is written with a method fly().
} ● The Parrot Class inherited the Bird Class using
} extends keyword.
// Inheriting SuperClass to SubClass
class Parrot extends Bird { ● An object of type parrot is created in the main
void whatColourAmI() { method of the main class. This object is able to call
System.out.println("I am green!"); the fly() method of the Bird class as it inherits the
} Bird class.
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
obj.whatColourAmI();
obj.fly();
}
}
Output:
I am green!
I am a Bird
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 83
Inheritance
2. Multilevel Inheritance in Java
This is an extension to single inheritance in java, where another class again inherits the subclass, which
inherits the superclass. The below figure makes this inheritance clear.
Ex: Below is a simple JAVA program that illustrates the Multilevel Inheritance
class Bird { Output:
void fly() { I can sing Opera!
System.out.println("I am a Bird");
}
I am green!
} I am a Bird
// Inheriting class Bird
class Parrot extends Bird { Explanation:
void whatColourAmI() {
System.out.println("I am green!"); ● Here in this program, the chain
}
} of inheritance is the Bird class is
// Inheriting class Parrot inherited by the Parrot class,
class SingingParrot extends Parrot {
void whatCanISing() {
and the Parrot class is, in turn,
System.out.println("I can sing Opera!"); inherited by the SingingParrot
} class.
}
class Main { ● The object of SingingParrot Here Subclass 2 can again
public static void main(String args[]) { created in the main method of be inherited by another
SingingParrot obj = new SingingParrot(); class, Subclass 3.
java will be able to access the
obj.whatCanISing(); This can keep on going
obj.whatColourAmI(); methods whatCanISing(), forming a linear chain of
obj.fly(); whatColourAmI(), fly() as they inheritances. This is called
} Multilevel inheritance in
are all inherited by java.
}
SingingParrot class using
multilevel
Department of Computer Science & Engineering, inheritance
VNRVJIET, Hyderabad in java.March 06, 2023 84
Inheritance
3. Hierarchical Inheritance in Java
In this inheritance, a single superclass is inherited separately by two or more subclasses.
The below figure illustrates thisEx:
inheritance:
Below is a simple JAVA program that illustrates the
Hierarchical Inheritance
class Bird { class Main {
void fly() { public static void
System.out.println("I am main(String args[]) {
a Bird"); Parrot par = new Parrot();
} Crow cro = new Crow();
} //Call methods of Parrot Class
class Parrot extends Bird { par.whatColourAmI();
void whatColourAmI() { par.fly();
System.out.println("I am
Explanation:
green!"); //Call methods of Crow Class
● The superclass Bird is inherited } cro.whatColourAmI();
separately by two different } cro.fly();
subclasses Parrot and Crow.
● The Parrot object can call its class Crow extends Bird { }
method whatColourAmI() and void whatColourAmI() { } Output:
also the fly() method, which is System.out.println("I am I am green!
inherited from the superclass
Bird. black!"); I am a Bird
● The Crow object can call its } I am black!
method whatColourAmI() and I am a Bird
also the fly() method, which is
}
inherited from the superclass
Bird. March 06, 2023 85
Department of Computer Science & Engineering, VNRVJIET, Hyderabad
Inheritance
4. Multiple Inheritance in java // Not Possible
In Multiple Inheritance, a single class inherits from two different superclasses. Multiple Inheritance
for classes is Invalid in java. class A {
void testMethod() {
System.out.println("I am from class A");
}
}
class B {
void testMethod() {
System.out.println("I am from class B");
}
}
// Not possible to inherit classes this way, But for understanding,
let us suppose
●
class C extends A, B {
Consider there is a superclass1
name A, and A class has a method void newMethod() {
testMethod(). And Consider there is System.out.println("I am from subclass");
a superclass2 named B, and B class }
has a method testMethod(), which }
has the same name as class A.
●
class Main {
Now, lets us suppose that classes A
and B are both inherited by a public static void main(String args[]) {
subclass named C. C obj = new C();
● And if testMethod() is called from obj.testMethod();
the subclass C, an Ambiguity would // Ambiguity here as it's present in both A and B class
arise as the same method is
}
present in both the superclasses.
} /* Note: The above program is just for understanding that multiple inheritance of classes is
invalid in java. */
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 86
Inheritance
5. Hybrid Inheritance in Java // not possible and Invalid in java
Hybrid inheritance is a combination of hierarchical inheritance and multiple inheritance. This is also not possible and Invalid
in java. The below figure illustrates the hybrid inheritance in java.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 87
Inheritance
Super Keyword
The super keyword is used to refer to the parent class of any class. This keyword can be
used to access the variables, methods, and constructors of the parent class from the
child class. Let us explore the usage of the super keyword using the below examples.
Ex1: Example program that illustrates access of parent class variable using
super keyword.
class TestParentClass { Output:
int var = 100; The var value of child: 50
} The var value of parent: 100
class TestChildClass extends TestParentClass {
int var = 50;
/*Same variable is present in both parent and child */
Explanation:
void display() {
System.out.println("The var value of child: " + var);
● Class TestChildClass inherits the
System.out.println("The var value of parent: " +super.var);
TestParentClass. Both classes have
/*using the super keyword will refer to parent class variables*/ a common variable, var. In such a
} conflict, priority is always given to
} the child class's variable.
class TestParentDemo {
● To access the variable of the
public static void main(String args[]) {
TestChildClass tcc = new TestChildClass(); parent class from the child class,
tcc.display(); we can make use of the keyword
}
}
super .
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 88
Inheritance
Super Keyword
Ex2: Example program that illustrates access of parent class methods using
super keyword.
class TestParentClass{
void test() {
Output:
System.out.println("This is a Parent test Method");
This is a Child test Method
}
This is a Parent test Method
}
class TestChildClass extends TestParentClass{
//The same method is present in the parent class. Explanation:
void test() {
System.out.println("This is a Child test Method"); ● The class TestChildClass
} inherited the TestParentClass,
void display() { both have a common method
test(); //This calls the method of TestChildClass test(). In this case, if you try to
super.test(); //This calls the method of TestParentClass access test() method from the
} child class, priority is given to the
}
child class's test() method.
class TestParentDemo1{
public static void main(String args[]){ ● So, to access the parent test()
TestChildClass tcc = new TestChildClass(); method from TestChildClass,
tcc.display(); we can make use of the super
} keyword.
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 89
Inheritance
Super Keyword
Ex3: Example program that illustrates access of parent class constructor using
super keyword. Output:
class TestParentClass {
TestParentClass() { ● This is the Parent class
System.out.println("This is the Parent class constructor");
constructor
} ● This is the Child class
}
constructor
class TestChildClass extends TestParentClass {
TestChildClass() { Explanation:
super();
● The super() call inside the child
System.out.println("This is the Child class constructor");
class constructor invokes the
}
constructor of the parent
}
class constructor. The super()
class TestParentDemo2 {
class can only be placed as
public static void main(String args[]) {
the first statement in the
TestChildClass tcc = new TestChildClass();
child class constructor.
}
● Note that the super() call is
}
implicit in java. Any child
constructor, when invoked,
automatically invokes the
parent constructor first, even
if no explicitly super() call is
placed in 2023
March 06, the child class 90
Department of Computer Science & Engineering, VNRVJIET, Hyderabad
constructor.
Inheritance
Super Keyword
Note: In the case of the parent class having a multiple-parameterized constructor, all the parameters
that are to be passed to the parent's constructor should be first passed to the child class constructor.
Then the parameters for the parent class should be passed in the super() call, thereby invoking the
parameterized constructor of the parent class. Below example, java program makes this point clear.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 91
Inheritance
Using final with Inheritance:
The keyword final has three uses.
First, it can be used to create the equivalent of a named constant.
This use was described in the preceding chapter. The other two uses of final apply to inheritance. Both are
examined here.
Using final to Prevent Overriding
▪ While method overriding is one of Java’s most powerful features, there will be times when you will want to
prevent it from occurring.
▪ To disallow a method from being overridden, specify final as a modifier at the start of its
declaration.
▪ Methods declared as final cannot be overridden. The following
Methods fragment
declared as final canillustrates
sometimesfinal:
provide a
performance enhancement: The compiler is free to inline
class A { calls to them because it “knows” they will not be
final void meth() { overridden by a subclass. When a small final method is
System.out.println("This is a final method.");
called, often the Java compiler can copy the bytecode for
} the subroutine directly inline with the compiled code of the
} calling method, thus eliminating the costly overhead
class B extends A { associated with a method call. Inlining is only an option
void meth() { // ERROR! Can't override.with final methods. Normally, Java resolves calls to
System.out.println("Illegal!"); methods dynamically, at run time. This is called late
} binding. However, since final methods cannot be
}Because meth( ) is declared as final, it cannot be overridden, a call to one can be resolved at compile time.
overridden in B. If you attempt to do This is called early binding.
so, a compile-time error will result.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 92
Inheritance
Using final to Prevent Inheritance
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 93
Inheritance
Access modifiers and how they affect inheritance
Below is how access modifiers public, private, protected and default affect the way the variables
and methods of the parent class are inherited by the child class
● Private:
Variables and methods declared private in the parent class cannot be inherited by child
classes. They can only be accessed in the parent class. By creating public getter and
setter methods, we can access these variables in the child class.
● Public:
Variables and methods declared as public in the parent class would be inherited by the
child class and can be accessed directly by the child class.
● Protected:
Variables and methods declared as protected in the parent class would be inherited by the
child class and can be accessed directly by the child class. But the access level is
limited to one subclass. So if the subclass is again inherited by another class, they will
not have access to those protected variables/methods.
● Default:
This is the case where no access modifier is specified. Variables and methods which have
default access modifiers in the parent class can be accessed by the child class.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 94
Method Overriding
▪ In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
▪ When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass.
▪ The version of the method defined by the superclass will be hidden.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 95
Inheritance
Conclusion
Below are some of the important points to keep in mind when
working with inheritance.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 96
Polymorphism
Let us understand the definition of polymorphism by an example; a lady can have different characteristics
simultaneously. She can be a mother, a daughter, or a wife, so the same lady possesses different behavior in
different situations.
Another example of polymorphism can be seen in carbon, as carbon can exist in many forms, i.e., diamond,
graphite, coal, etc. We can say that both woman and carbon show different characteristics at the same time
according to the situation. This is called polymorphism.
The definition of polymorphism can be explained as performing a single task in different ways. A single interface
having multiple implementations is also called polymorphism.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 97
Polymorphism
/* Parent class to illustrate run-time polymorphism*/ public class PolymorphDemo {
class Parent { public static void main(String[] args) {
// creating print method // creating instance of parent
void print() { Parent obj1;
System.out.println("Hi I am parent"); obj1 = new Parent();
} obj1.print();
} obj1 = new Child();
// Child class extends Parent class obj1.print();
class Child extends Parent {
// overriding print method // creating instance of overload
void print() { Overload obj2 = new Overload();
System.out.println("Hi I am children"); obj2.statement("Soham.");
} obj2.statement("Soham", "Medewar.");
} }
// Overload class to illustrate compile-time polymorphism }
class Overload {
Output:
// Creating a statement method
void statement(String name) {
System.out.println("Hi myself " + name);
}
// overloading statement method Hi I am a parent
void statement(String fname, String lname) {
Hi I am children
System.out.println("Hi myself " + fname + " "
+ lname); Hi myself Soham.
} Hi myself Soham Medewar.
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 98
Polymorphism
// parent class Bank
class PolymorphismDemo1{
class Bank{
// creating rateOfInterest method public static void main(String[] args){
float rateOfInterest(){ // creating variable of Bank class
return 0;
} Bank B;
} B = new ICICI();
// ICICI class extends Bank class
class ICICI extends Bank{ System.out.println("Rate of interest of
// overriding rateOfInterest method ICICI is: "+B.rateOfInterest());
float rateOfInterest(){
return 5.5f; B = new SBI();
} System.out.println("Rate of interest
}
// SBI class extends Bank class
of . SBI is: "+B.rateOfInterest());
class SBI extends Bank{ B = new HDFC();
// overriding rateOfInterest method
float rateOfInterest(){
System.out.println("Rate of interest
return 10.6f; of
}
HDFC is: "+B.rateOfInterest());
}
// HDFC class extends Bank class }
class HDFC extends Bank{ }
// overriding rateOfInterest method
float rateOfInterest(){ Output:
return 9.4f; Rate of interest of ICICI is: 5.5
}
Rate of interest of SBI is: 10.6
}
Rate of interest of HDFC is: 9.4
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 99
Polymorphism
Using Data Members : data members are not overridden, so data members can't
achieve polymorphism.
// Parent class
class Parent{
int value = 50;
}
// Child class extends Parent class
class Child extends Parent{
int value = 100;
}
class PolymorphismDataMember{
public static void main(String[] args) {
// creating new object of Parent class
Parent obj1 = new Child();
System.out.println("Child value : "+obj1.value);
}
}
Output:
Child value : 50
Explanation:
In the above example, we can see that value in the child class is not overrode, as the "value"
remains 50 after overriding.
The above program concludes that data members are not overridden, so data members can't
Department of Computer Science & Engineering, VNRVJIET, Hyderabad
achieve polymorphism. March 06, 2023 100
Polymorphism
In Java, the ‘+’ symbol is used to add two numbers or used to
concatenate two strings.
class Polymorphism{
public static void main(String[] args) {
// adding numbers
int num1 = 741, num2 = 852;
String str1 = "Hello", str2 = "World!";
// concatenating two strings
int sum = num1+num2;
String final_str = str1 + str2;
System.out.println("Sum = "+sum);
System.out.println("Final String = "+final_str);
}
}
Output
Sum = 1593
Final String = HelloWorld!
Explanation
In the above example, the ‘+’ operator is performing both addition and
concatenation tasks.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 101
Dynamic Method Dispatch
Method overriding forms the basis for one of Java’s most powerful concepts:
dynamic method dispatch.
Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
Dynamic method dispatch is important because this is how Java implements
run-time polymorphism.
Let’s begin by restating an important principle:
▪ a superclass reference variable can refer to a subclass object.
▪ Java uses this fact to resolve calls to overridden methods at run time.
▪ Here is how. When an overridden method is called through a superclass
reference, Java determines which version of that method to execute
based upon the type of the object being referred to at the time the call
occurs.
▪ Thus, this determination is made at run time.
▪ When different types of objects are referred to, different versions of an
overridden method will be called.
▪ In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an
overridden method will be executed.
▪ Therefore, if a superclass contains a method that is overridden by a
subclass, then when different types of objects are referred to through a
superclass reference variable,
Department of Computer different
Science & Engineering, versions
VNRVJIET, Hyderabad of the
Marchmethod
06, 2023 are 102
Dynamic Method Dispatch
Here is an example that illustrates dynamic method dispatch:
class A { // Dynamic Method Dispatch class Dispatch {
void callme() { public static void main(String args[]) {
System.out.println("Inside A's callme method"); A a = new A(); // object of type A
} B b = new B(); // object of type B
} C c = new C(); // object of type C The output from the
class B extends A { program is shown here:
A r; // obtain a reference of type A
void callme() { // override callme()
r = a; // r refers to an A object Inside A’s callme method
System.out.println("Inside B's callme
method"); r.callme(); // calls A's version of callme Inside B’s callme method
} r = b; // r refers to a B object Inside C’s callme method
} r.callme(); // calls B's version of callme
class C extends A { r = c; // r refers to a C object
void callme() { // override callme() r.callme(); // calls C's version of callme
System.out.println("Inside C's callme }
method"); }
}
}
This program creates one superclass called A and two subclasses of it, called B and C.
Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of type A, B, and C are declared.
Also, a reference of type A, called r, is declared. The program then in turn assigns a reference to each type of object to r
and uses that reference to invoke callme( ). As the output shows, the version of callme( ) executed is determined by the
type of object being referred to at the time of the call. Had it been determined by the type of the reference variable, r,
you would see three calls to A’s callme( ) method.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 103
Abstract Classes
Using Abstract Classes
▪ There are situations in which you will want to define a superclass that declares the structure
of a given abstraction without providing a complete implementation of every method.
▪ That is, sometimes you will want to create a superclass that only defines a generalized form
that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
▪ Such a class determines the nature of the methods that the subclasses must implement.
▪ One way this situation can occur is when a superclass is unable to create a meaningful
implementation for a method.
▪ You can handle this situation two ways.
▪ One way, as shown in the previous example, is to simply have it report a warning
message. While this approach can be useful in certain situations—such as debugging—
it is not usually appropriate.
▪ You may have methods that must be overridden by the subclass in order for the
subclass to have any meaning.
▪ Consider the class Triangle. It has no meaning if area( ) is not defined. In this case, you want
some way to ensure that a subclass does, indeed, override all necessary methods.
▪ Java’s solution to this problem is the abstract method.
▪ You can require that certain methods be overridden by subclasses by specifying the abstract
type modifier.
▪ These methods are sometimes referred to as subclasser responsibility because they have no
implementation specified in the superclass.
▪ Thus, a subclass must override them—it cannot simply use the version defined in the
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 104
superclass.
Abstract Classes
Using Abstract Classes
▪ As you can see, no method body is present. Any class that contains
one or more abstract methods must also be declared abstract.
▪ To declare a class abstract, you simply use the abstract keyword in
front of the class keyword at the beginning of the class declaration.
▪ There can be no objects of an abstract class. That is, an abstract
class cannot be directly instantiated with the new operator.
▪ Such objects would be useless, because an abstract class is not fully
defined.
▪ Also, you cannot declare abstract constructors, or abstract static
methods.
▪ Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be itself declared
Department of Computer Science & Engineering, VNRVJIET, Hyderabad
abstract.105
March 06, 2023
Abstract Classes
Here is a simple example of a class with an abstract method, followed by a class which implements that method:
// A Simple demonstration of abstract.
abstract class A { Notice that no objects of class A are declared in the
abstract void callme();
program. As mentioned, it is not possible to instantiate
an abstract class.
One other point: class A implements a concrete method
// concrete methods are still allowed in abstract classes
void callmetoo() { called callmetoo( ). This is perfectly acceptable.
System.out.println("This is a concrete method.");Abstract classes can include as much implementation as
} they see fit.
}
class B extends A {
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 106
Abstract Classes
Using an abstract class, you can improve the Figure class shown earlier. Since there is no meaningful concept of
area for an undefined two-dimensional figure, the following version of the program declares area( ) as abstract
inside Figure. This, of course, means that all classes derived from Figure must override area( ).
// Using abstract methods and classes. class Triangle extends Figure { As the comment inside main( )
indicates, it is no longer
abstract class Figure { Triangle(double a, double b) {
possible to declare objects of
double dim1; super(a, b); type Figure, since it is now
double dim2; } abstract. And, all subclasses of
Figure(double a, double b) { // override area for right triangle Figure must override area( ).
dim1 = a; double area() { To prove this to yourself, try
dim2 = b; System.out.println("Inside Area for Triangle."); creating a subclass that does
not override area( ). You will
} return dim1 * dim2 / 2; receive a compile-time error.
// area is now an abstract method } Although it is not possible to
abstract double area(); } create an object of type
} class AbstractAreas { Figure, you can create a
class Rectangle extends Figure { public static void main(String args[]) { reference variable of type
Figure. The variable figref is
Rectangle(double a, double b) { // Figure f = new Figure(10, 10); // illegal now
declared as a reference to
super(a, b); Rectangle r = new Rectangle(9, 5); Figure, which means
} Triangle t = new Triangle(10, 8); that it can be used to refer to
// override area for rectangle Figure figref; // this is OK, no object is created an object of any class derived
double area() { figref = r; from Figure. As explained, it is
System.out.println("Inside Area for Rectangle."); System.out.println("Area is " + figref.area()); through superclass reference
figref = t; variables that overridden
return dim1 * dim2; methods are resolved at run
} System.out.println("Area is " + figref.area());
time.
} }
}
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 107
Exploring String class
▪ The use of strings is essential to programming. Java has a String class that allows for the creation and manipulation
of strings.
▪ The character sequence can also be represented using an interface called CharSequence.
▪ One of the classes that implements this interface is the String class.
▪ Thus, in Java, a string is an object that is essentially a sequence of characters.
For instance, the word "hello" is made up of a string of the characters "h," "e," "l," "l," and "o." Additionally, we have a
variety of String methods that make it simple to interact with String in Java.
By String Literal
The most typical method of producing string is this one. In this instance, double quotes are
used to surround a string literal.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 109
Exploring String class
Constructors of String Class in Java
1. String()
produces a blank string. Due to the immutability of String, it is largely worthless.
2. String(String original)
from another string, generates a string object. String is useless since it is immutable.
3. String(byte[] bytes)
creates a new string using the system's default encoding from the byte array.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 110
Exploring String class
Constructors of String Class in Java
8. String(byte bytes[], int offset, int length, String charsetName)
The character set encoding name is supplied as a string, unlike the example before. If the encoding is not supported, this
will throw an UnsupportedEncodingException.
9. String(char value[])
uses the character array to generate the string object.
1 char charAt(int index) It provides a char value for the specified index.
2 int length() return the length of string
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 112
Exploring String class
Methods of String Class in Java
Sl No Method Description
It determines whether the string and the
10 boolean equals(Object another) supplied object are equal.
11 boolean isEmpty() check if string is empty or not.
It concatenates the string with the supplied
12 String concat(String str) string.
13 String replace(char old, char new) It replaces the old char with the new char.
It changes the supplied CharSequence
14 String replace(CharSequence old, CharSequence new) anywhere it appears.
It compares a different string. Case is not
15 static String equalsIgnoreCase(String another) checked.
16 String[] split(String regex) A split string that matches the regex is returned.
It gives back a split string that matches limit and
17 String[] split(String regex, int limit) regex.
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 113
Exploring String class
Methods of String Class in Java
Sl No Method Description
Starting with the supplied index, it returns the
20 int indexOf(int ch, int fromIndex) specified char value index.
21 int indexOf(String substring) The requested substring index is returned.
The required substring index beginning with the
22 int indexOf(String substring, int fromIndex) supplied index is returned.
24 String toLowerCase(Locale l)
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 114
Exploring String class
Examples of String Class in Java
// Returns the index within the string
// of the first occurrence of the specified string.
String s4 = "Hello World";
Example 1 System.out.println("Index of World is " +
s4.indexOf("World"));
In this example we are going to discuss some methods of string class in java // Returns the index within the string of the
// first occurrence of the specified string,
// starting at the specified index.
// Java code to explain different constructors and methods // String System.out.println("Index of o in Hello World = " +
class. s4.indexOf('o',3));
import java.io.*;
// Checking equality of Strings
import java.util.*;
Boolean out = "HELLO".equals("hello");
public class str{ System.out.println("Checking Equality of HELLO and hello " + out);
public static void main (String[] args){ out = "HELLO".equals("HELLO");
// created string using string literal System.out.println("Checking Equality " + out);
String s= "HelloWorld"; out = "HeLlo".equalsIgnoreCase("Hello");
// Returns the number of characters in the String. System.out.println("Checking Equality " + out);
System.out.println("length of "+s+"is" + s.length());
//If ASCII difference is zero then the two strings are similar
int out1 = s1.compareTo(s2);
// Returns the character at ith index. System.out.println("the difference between ASCII value is="+out1);
System.out.println("Character at 2nd position = "+ s.charAt(2)); // Converting cases
String word1 = "World";
System.out.println("Changing to lower Case " +
// Return the substring from the ith index character word1.toLowerCase());
// to end of string
System.out.println("Substring from index 3 is " + // Converting cases
String word2 = "world";
s.substring(3)); System.out.println("Changing to UPPER Case " +
word2.toUpperCase());
// Returns the substring from i to j-1 index.
System.out.println("Substring from index 2 to index 4 = " + // Trimming the word
String word4 = " Welcome to Java ";
s.substring(2,5)); System.out.println("Trim the word " + word4.trim());
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 115
Exploring String class
Examples of String Class in Java
Example 1
In this example we are going to discuss some methods of string class in java
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 116
Exploring String class
Conclusion
● Strings are objects in Java that internally consist of a string of
characters. Simply put, a string is a grouping or arrangement of
characters.
● Newly created strings are kept in a specific location in the heap known
as the String Constant Pool or String Pool.
● Since strings are considered objects in Java, they can be generated
using both the new keyword and string literals.
● Java has a variety of methods for Strings that can be used to make
working with strings in Java simple.
● The + operator and Java's concat() function are the two methods for
concatenating strings.
● Since strings in Java are immutable, their value cannot be modified once
it has been initialised (or created).
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 117
THANK YOU
Department of Computer Science & Engineering, VNRVJIET, Hyderabad March 06, 2023 118