0% found this document useful (0 votes)
1 views50 pages

Java Module2

This document introduces the concepts of classes, objects, and methods in Java, explaining how classes serve as blueprints for creating objects with shared attributes and behaviors. It covers the syntax for creating classes and objects, the role of reference variables, and the structure of methods, including predefined and user-defined methods. Additionally, it discusses method parameters, return values, and the significance of the main() method as the entry point of Java programs.

Uploaded by

Prerna Janavekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views50 pages

Java Module2

This document introduces the concepts of classes, objects, and methods in Java, explaining how classes serve as blueprints for creating objects with shared attributes and behaviors. It covers the syntax for creating classes and objects, the role of reference variables, and the structure of methods, including predefined and user-defined methods. Additionally, it discusses method parameters, return values, and the significance of the main() method as the entry point of Java programs.

Uploaded by

Prerna Janavekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

UNIT II:

Introducing Classes, Objects and Methods

Class is a set of object which shares common characteristics/


behavior and common properties/ attributes
Everything in Java is associated with classes and objects, along
with its attributes and methods. For example: in real life, a car
is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.

Create a Class

To create a class, use the keyword class:


Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}
Classes and Objects are basic concepts of Object Oriented
Programming that revolve around real life entities.
Class
1. Class is a set of object which shares common
characteristics/ behavior and common properties/ attributes.
2. Class is not a real world entity. It is just a template or
blueprint or prototype from which objects are created.
3. Class does not occupy memory.
4. Class is a group of variables of different data types and
group of methods.
A class in java can contain:
•data member
• method
• constructor
• nested class and
• interface
Syntax to declare a class:
access_modifier class<class_name>
{
data member;
method;
constructor;
nested class;
interface;
}
Eg:
• Animal
• Student
• Bird
• Vehicle
• Company

Here, we are creating a main() method inside the class.


File: Student.java

1. //Java Program to illustrate how to define a class and fields

2. //Defining a Student class.


3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Studen
t
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through ref
erence variable
13. System.out.println(s1.name);
14. }
15. }

Output:
0
null

A class is a user-defined blueprint or prototype from which


objects are created. It represents the set of properties or
methods that are common to all objects of one type. In
general, class declarations can include these components, in
order:
1. Modifiers: A class can be public or has default access
(Refer this for details).
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter
(capitalized by convention).
4. Superclass(if any): The name of the class’s parent
(superclass), if any, preceded by the keyword extends. A class
can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body is surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are
variables that provide the state of the class and its objects,
and methods are used to implement the behavior of the class
and its objects.

How Objects are Created


Create an Object
In Java, an object is created from a class. We have already
created the class named Main, so now we can use this to create
objects.
To create an object of Main, specify the class name, followed by
the object name, and use the keyword new:
Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}
Output:5

The object is a basic building block of an OOPs language.


In Java, we cannot execute any program without creating
an object. There is various way to create an object in
Java that we will discuss in this section, and also learn how to
create an object in Java.
Java provides five ways to create an object.
o Using new Keyword
o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization

Using new Keyword


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

1. ClassName object = new ClassName();


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

Output:
Welcome to javaTpoint
Reference Variables and Assignment

A variable that holds reference of an object is called


a reference variable. Variable is a name that is used to hold a
value of any type during program execution. If the type is an
object, then the variable is called reference variable, and if the
variable holds primitive types(int, float, etc.), then it is called
non-reference variables.
For example, If we create a variable to hold a String object,
then it is called reference variable because String is a class.
See an example.
1
2String str = "Java2blog"; // str is reference variable
3MyClass mCl = new MyClass(); // mCl is reference variable
4int a = 10; // non-reference variable
5

Reference variable basically points to an object stored into


heap memory.

class MyClass{

void showMyName(String name) {


System.out.println("Your name is "+name);
}
}
public class Demo {

public static void main(String[] args){


// Creating reference to hold object of MyClass
MyClass myClass = new MyClass();
myClass.showMyName("Java2blog");
}
}

Output:
Your name is Java2blog
Reference variable can be of many types based on their scope
and accessibility. For example,
1. Static reference variable
2. Instance reference variable
3. Local reference variable

Static Reference Variable


A variable defined using static keyword is called static variable.
Static variable can be a reference or non-reference as well. In
this example, we created two static reference variables and
access them inside the main() method.
1
2 public class Demo {
3 // Static reference variables
4 static String str;
5 static String str2 = "Java2blog";
6
7 public static void main(String[] args){
8 System.out.println("Value of str : "+str);
9 System.out.println("Value of str2 : "+str2);
1 }
0 }
1
1
1
2
Output
Value of str : null
Value of str2 : Java2blog

Instance Reference Variable


A variable which is not static and defined inside a class is called
an instance reference variable. Since instance variable belongs
to object, then we need to use reference variable to call
instance variable.
1
2 public class Demo {
3 // instance reference variables
4 String str;
5 String str2 = "Java2blog";
6
7 public static void main(String[] args){
8 Demo demo = new Demo();
9 System.out.println("Value of str : "+demo.str);
1 System.out.println("Value of str2 : "+demo.str2);
0 }
1 }
1
1
2
1
3
Output
Value of str : null
Value of str2 : Java2blog

Local Reference Variable


Reference variable can be declared as local variable. For
example, we created a reference of String class in main()
method as local reference variable.
1
2 public class Demo {
3
4 public static void main(String[] args){
5 // Local reference variables
6 String str2 = "Java2blog";
7 System.out.println("Value of str2 : "+str2);
8 }
9 }
1
0
Output:
Value of str2 : Java2blog
method
A method is a block of code or collection of statements or a set
of code grouped together to perform a certain task or
operation. It is used to achieve the reusability of code. We
write a method once and use it many times. We do not require
to write code again and again. It also provides the easy
modification and readability of code, just by adding or
removing a chunk of code. The method is executed only when
we call or invoke it.

The most important method in Java is the main() method. If


you want to read more about the main() method

Method Declaration
The method declaration provides information about method
attributes, such as visibility, return-type, name, and arguments.
It has six components that are known as method header, as
we have shown in the following figure.

Method Signature: Every method has a method signature. It


is a part of the method declaration. It includes the method
name and parameter list.
Access Specifier: Access specifier or modifier is the access
type of the method. It specifies the visibility of the method. Java
provides four types of access specifier:

o Public: The method is accessible by all classes when we use public


specifier in our application.
o Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
o Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible
only from the same package only.

Return Type: Return type is a data type that the method


returns. It may have a primitive data type, object, collection,
void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the


name of a method. It must be corresponding to the
functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name must
be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a


comma and enclosed in the pair of parentheses. It contains the
data type and variable name. If the method has no parameter,
left the parentheses blank.

Method Body: It is a part of the method declaration. It


contains all the actions to be performed. It is enclosed within
the pair of curly braces.

Types of Method
There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method
In Java, predefined methods are the method that is already
defined in the Java class libraries is known as predefined
methods. It is also known as the standard library
method or built-in method. We can directly use these
methods just by calling them in the program at any point. Some
pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc. When we call any of the predefined methods in our
program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class.


Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we
write inside the method. For example, print("Java"), it prints
Java on the console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


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

Output:
The maximum number is: 9

User-defined Method
The method written by the user or programmer is known as a
user-defined method. These methods are modified according
to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is


even or odd. First, we will define the method.

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

Output:
The sum of a and b is= 24
Returning from a Method, Returning Value

The public static void main() method is the entry point of


the Java program. Whenever you execute a program in Java,
the JVM searches for the main method and starts executing
from it.
You can write the main method in your program with return
type other than void, the program gets compiled without
compilation errors.
But, at the time of execution JVM does not consider this new
method (with return type other than void) as the entry point of
the program.
It searches for the main method which is public, static, with
return type void, and a String array as an argument.
public static int main(String[] args){
}
If such a method is not found, a run time error is generated.
Example
In the following Java program, we are trying to write the main
method with the return type integer −
import java.util.Scanner;
public class Sample{
public static int main(String[] args){
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("This is a sample program");
return num;
}
}

Output
On executing, this program generates the following error −
Error: Main method must return a value of type void in class Sample,
please
define the main method as:
public static void main(String[] args)

Using Parameters

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as
variables inside the method.

Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

public class Main {

static void myMethod(String fname) {

System.out.println(fname + " aaa");

public static void main(String[] args) {

myMethod("ram");

myMethod("Jenny");

myMethod("deepa");

// ram aaa

// Jenny aaa
// deepa aaa

When a parameter is passed to the method, it is called an argument. So,


from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.

Multiple Parameters
You can have as many parameters as you like:

public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " +age);

public static void main(String[] args) {

myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31
Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:

public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

System.out.println(myMethod(3));

// Outputs 8

Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes:

Syntax
Following is the syntax of a constructor −
class ClassName {
ClassName() {
}
}
Java allows two types of constructors namely −

 No argument Constructors
 Parameterized Constructors
Rules for creating Java constructor
There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any
parameter.

Syntax of default constructor:

1. <class_name>(){}
Example of 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.

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1()
5. {
6. System.out.println("Bike is created");}
7. //main method
8. public static void main(String args[]){
9. //calling a default constructor
10.Bike1 b=new Bike1();
11. }
12.}

Output:

Bike is created

Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to


distinct objects. However, you can provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that
have two parameters. We can have any number of parameters in the
constructor.
1. //Java Program to demonstrate the use of the parameterized constru
ctor.
2. class Student{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){
12. System.out.println(id+" "+name);
13. }
14. public static void main(String args[]){
15. //creating objects and passing values
16. Student s1 = new Student4(111,"Karan");
17. Student s2 = new Student4(222,"Aryan");
18. //calling method to display the values of object
19. s1.display();
20. s2.display();
21. }
22. }

Output:

111 Karan
222 Aryan

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.
Advantage of Garbage Collection

o It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.

finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:

1. protected void finalize(){}


gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.

1. public static void gc(){}

Simple Example of garbage collection in java


1. public class TestGarbage{
2. public void finalize()
3. {
4. System.out.println("object is garbage collected");}
5. public static void main(String args[]){
6. TestGarbage s1=new TestGarbage();
7. TestGarbage s2=new TestGarbage();
8. s1=null;
9. s2=null;
10. System.gc();
11. }
12.}

object is garbage collected


object is garbage collected
This Keyword
Using this with a class attribute (x):

public class Main {

int x;

// Constructor with a parameter

public Main(int x) {

this.x = x;

// Call the constructor

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println("Value of x = " + myObj.x);

Value of x = 5

A Closer Look at Methods and Classes


Controlling Access to Class Members
There are two types of modifiers in Java: access modifiers and non-
access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field,


method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you do
not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do not
make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can
be accessed from within the class, outside the class, within the
package and outside the package.

There are many non-access modifiers, such as static, abstract,


synchronized, native, volatile, transient, etc. Here, we are going to learn
the access modifiers only.

Understanding Java Access Modifiers


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

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private
The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class


contains private data member and private method. We are accessing
these private members from outside the class, so there is a compile-time
error.

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

Pass Objects to Methods


Although Java is strictly passed by value, the precise effect differs between
whether a primitive type or a reference type is passed. When we pass a
primitive type to a method, it is passed by value. But when we pass an object
to a method, the situation changes dramatically, because objects are passed
by what is effectively call-by-reference. Java does this interesting thing that’s
sort of a hybrid between pass-by-value and pass-by-reference.
Basically, a parameter cannot be changed by the function, but the function
can ask the parameter to change itself via calling some method within it.
 While creating a variable of a class type, we only create a reference
to an object. Thus, when we pass this reference to a method, the
parameter that receives it will refer to the same object as that
referred to by the argument.
 This effectively means that objects act as if they are passed to
methods by use of call-by-reference.
 Changes to the object inside the method do reflect the object used as
an argument

// Java Program to Demonstrate Objects Passing to Methods.

// Class
// Helper class
class ObjectPassDemo {
int a, b;

// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}

// Method
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method

return (o.a == a && o.b == b);


}
}

// Main class
public class GFG {
// MAin driver method
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

// Checking whether object are equal as custom


// values
// above passed and printing corresponding boolean
// value
System.out.println("ob1 == ob2: "
+ ob1.equalTo(ob2));
System.out.println("ob1 == ob3: "
+ ob1.equalTo(ob3));
}
}

Output
ob1 == ob2: true
ob1 == ob3: false

Returning Objects
a method can return any type of data, including class types that you can
create. For example, in the following Java program, the
method incrByTen() returns an object in which the value of a is ten greater
than it is in the invoking object.

Java Returning Objects Example


/* Java Program Example - Java Returning Objects
* Returning an object */

class Test
{
int a;

Test(int i)
{
a = i;
}

Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}

public class JavaProgram


{
public static void main(String args[])
{

Test obj1 = new Test(2);


Test obj2;

obj2 = obj1.incrByTen();

System.out.println("obj1.a : " + obj1.a);


System.out.println("obj2.a : " + obj2.a);

obj2 = obj2.incrByTen();

System.out.println("obj2.a after second increase : " +


obj2.a);

}
}

When the above Java program is compile and executed, it will produce the
following output:
Method Overloading
If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.

If we have to perform only one operation, having same name of the


methods increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can
be any number of arguments, if you write the method such as a(int,int) for
two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior
of the method because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method
performs addition of two numbers and second add method performs
addition of three numbers.

In this example, we are creating static methods so that we don't need to


create instance for calling methods.
class MethodOverloadingEx {

static int add(int a, int b)


{
return a + b;
}

static int add(int a, int b, int c)


{
return a + b + c;
}

public static void main(String args[])


{
System.out.println("add() with 2 parameters");
System.out.println(add(4, 6));

System.out.println("add() with 3 parameters");


System.out.println(add(4, 6, 7));
}
}

Output
add() with 2 parameters
10
add() with 3 parameters
17

Method Overriding:
Method Overriding is a Run time polymorphism. In method overriding, the
derived class provides the specific implementation of the method that is
already provided by the base class or parent class. In method overriding, the
return type must be the same or co-variant (return type may vary in the same
direction as the derived class).
Example: Method Overriding

Method Overriding
Consider a scenario where Bank is a class that provides functionality to
get the rate of interest. However, the rate of interest varies according to
banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%, and
9% rate of interest.
Java method overriding is mostly used in Runtime Polymorphism which we will
learn in next pages.
1. //Java Program to demonstrate the real scenario of Java Method Ove
rriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10.}
11.
12.class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14.}
15. class AXIS extends Bank{
16.int getRateOfInterest(){return 9;}
17. }
18.//Test class to create objects and call the methods
19. class Test2{
20.public static void main(String args[]){
21. SBI s=new SBI();
22.ICICI i=new ICICI();
23. AXIS a=new AXIS();
24.System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfIntere
st());
26.System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28.}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

The differences between Method Overloading and Method Overriding in Java


are as follows:

Method Overloading Method Overriding

Method overloading is a compile-time Method overriding is a run-time


polymorphism. polymorphism.

It is used to grant the specific


implementation of the method which is
It helps to increase the readability of already provided by its parent class or
the program. superclass.

It is performed in two classes with


It occurs within the class. inheritance relationships.

Method overloading may or may not Method overriding always needs


require inheritance. inheritance.

In method overloading, methods must


have the same name and different In method overriding, methods must have
signatures. the same name and same signature.

In method overloading, the return type


can or can not be the same, but we just In method overriding, the return type
have to change the parameter. must be the same or co-variant.
Method Overloading Method Overriding

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

It gives better performance. The reason


behind this is that the binding of
Poor Performance due to compile time overridden methods is being done at
polymorphism. runtime.

Private and final methods can be Private and final methods can’t be
overloaded. overridden.

Argument list should be different while Argument list should be same in method
doing method overloading. overriding.

Overloading Constructors
Java supports constructor overloading. In constructor
loading, we create multiple constructors with the same
name but with different parameters types or with different
no of parameters.
public class Tester {

private String message;

public Tester(){
message = "Hello World!";
}
public Tester(String message){
this.message = message;
}
public String getMessage(){
return message ;
}
public void setMessage(String message){
this.message = message;
}
public static void main(String[] args) {
Tester tester = new Tester();
System.out.println(tester.getMessage());

Tester tester1 = new Tester("Welcome");


System.out.println(tester1.getMessage());
}
}

Output
Hello World!
Welcome

Recursion
Recursion in java is a process in which a method calls itself continuously.
A method in java that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

1. returntype methodname(){
2. //code to be executed
3. methodname();//calling same method
4. }
Java Recursion Example 1: Finite times
1. public class RecursionExample {
2. static int count=0;
3. static void p(){
4. count++;
5. if(count<=5){
6. System.out.println("hello "+count);
7. p();
8. }
9. }
10.public static void main(String[] args) {
11. p();
12.}
13. }

Output:

hello 1
hello 2
hello 3
hello 4
hello 5

Java Recursion Example 3: Factorial Number


1. public class RecursionExample{
2. static int factorial(int n){
3. if (n == 1)
4. return 1;
5. else
6. return(n * factorial(n-1));
7. }
8.
9. public static void main(String[] args) {
10.System.out.println("Factorial of 5 is: "+factorial(5));
11. }
12.}

Output:

Factorial of 5 is: 120


Understanding Static
The static keyword in Java is used for memory management mainly. We
can apply static keyword with variables, methods, blocks and nested
classes. The static keyword belongs to the class than an instance of the
class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable


If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the company
name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of
class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data
members will get memory each time when the object is created. All
students have its unique rollno and name, so instance data member is
good in such case. Here, "college" refers to the common property of
all objects. If we make it static, this field will get the memory only once.

Example of static variable

1. //Java Program to demonstrate the use of static variable


2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14.//Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of
code
20. s1.display();
21. s2.display();
22. }
23.}

Output:

111 Karan ITS


222 Aryan ITS

Introducing Nested and Inner Classes


In Java, you can define a class within another class. Such class is known
as nested class . For example,

class OuterClass {
// ...
class NestedClass {
// ...
}
}

There are two types of nested classes you can create in Java.

 Non-static nested class (inner class)

 Static nested class

Recommended reading:
 Java Access Modifiers
 Java Static Keyword
Non-Static Nested Class (Inner Class)

A non-static nested class is a class within another class. It has access to


members of the enclosing class (outer class). It is commonly known
as inner class .

Since the inner class exists within the outer class, you must instantiate the
outer class first, in order to instantiate the inner class.
Here's an example of how you can declare inner classes in Java.

Example 1: Inner class


class CPU {
double price;
// nested class
class Processor{

// members of nested class


double cores;
String manufacturer;

double getCache(){
return 4.3;
}
}

// nested protected class


protected class RAM{

// members of protected nested class


double memory;
String manufacturer;

double getClockSpeed(){
return 5.5;
}
}
}

public class Main {


public static void main(String[] args) {

// create object of Outer class CPU


CPU cpu = new CPU();
// create an object of inner class Processor using outer class
CPU.Processor processor = cpu.new Processor();

// create an object of inner class RAM using outer class CPU


CPU.RAM ram = cpu.new RAM();
System.out.println("Processor Cache = " +
processor.getCache());
System.out.println("Ram Clock speed = " + ram.getClockSpeed());
}
}

Output:

Processor Cache = 4.3


Ram Clock speed = 5.5

Varargs: Variable-Length Arguments.


he varrags allows the method to accept zero or muliple arguments. Before
varargs either we use overloaded method or take an array as the method
parameter but it was not considered good because it leads to the
maintenance problem. If we don't know how many argument we will have
to pass in the method, varargs is the better approach.

Advantage of Varargs:
We don't have to provide overloaded methods so less code.

Syntax of varargs:
The varargs uses ellipsis i.e. three dots after the data type. Syntax is as
follows:

1. return_type method_name(data_type... variableName){}

EXAMPLE:
public class Demo {
public static void Varargs(String... str) {
System.out.println("\nNumber of arguments are: " +
str.length);
System.out.println("The argument values are: ");
for (String s : str)
System.out.println(s);
}

public static void main(String args[]) {


Varargs("Apple", "Mango", "Pear");
Varargs();
Varargs("Magic");
}
}
OUTPUT
Number of arguments are: 3

The argument values are:

Apple

Mango

Pear

Number of arguments are: 0

The argument values are:

Number of arguments are: 1

The argument values are:

Magic

Inheritance: Inheritance Basics


Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create


new classes that are built upon existing classes. When you inherit from an
existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.

Why use inheritance in java

o For Method Overriding


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.

syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

Java Inheritance Example


Example:
class Employee{

float salary=40000;

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

Output

Programmer salary is:40000.0


Bonus of Programmer is:10000

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported


through interface only. We will learn about interfaces later.
When one class inherits multiple classes, it is known as multiple
inheritance. For Example:

Inheritance and Constructors

Constructors in Java are used to initialize the values of the attributes of


the object serving the goal to bring Java closer to the real world. We
already have a default constructor that is called automatically if no
constructor is found in the code. But if we make any constructor say
parameterized constructor in order to initialize some attributes then it
must write down the default constructor because it now will be no more
automatically called.

1. Order of execution of constructor in Single inheritance


In single level inheritance, the constructor of the base class is executed
first.

OrderofExecution1.java

1. /* Parent Class */
2. class ParentClass
3. {
4. /* Constructor */
5. ParentClass()
6. {
7. System.out.println("ParentClass constructor executed.");
8. }
9. }
10.
11. /* Child Class */
12. class ChildClass extends ParentClass
13. {
14. /* Constructor */
15. ChildClass()
16. {
17. System.out.println("ChildClass constructor executed.");
18. }
19. }
20.
21. public class OrderofExecution1
22. {
23. /* Driver Code */
24. public static void main(String ar[])
25. {
26. /* Create instance of ChildClass */
27. System.out.println("Order of constructor execution...");
28. new ChildClass();
29. }
30. }

Output:

Order of constructor execution...


ParentClass constructor executed.
ChildClass constructor executed.

2. Order of execution of constructor in Multilevel inheritance


In multilevel inheritance, all the upper class constructors are executed
when an instance of bottom most child class is created.

OrderofExecution2.java

1. class College
2. {
3. /* Constructor */
4. College()
5. {
6. System.out.println("College constructor executed");
7. }
8. }
9.
10. class Department extends College
11. {
12. /* Constructor */
13. Department()
14. {
15. System.out.println("Department constructor executed");
16. }
17. }
18.
19. class Student extends Department
20. {
21. /* Constructor */
22. Student()
23. {
24. System.out.println("Student constructor executed");
25. }
26. }
27. public class OrderofExecution2
28. {
29. /* Driver Code */
30. public static void main(String ar[])
31. {
32. /* Create instance of Student class */
33. System.out.println("Order of constructor execution in Mul
tilevel inheritance...");
34. new Student();
35. }
36. }

Output:

Order of constructor execution in Multilevel inheritance...


College constructor executed
Department constructor executed
Student constructor executed

Using super to Call Superclass constructors


In inheritance constructors are not inherited. You need to call them
explicitly using the super keyword.
If a Super class have parameterized constructor. You need to accept
these parameters in the sub class’s constructor and within it, you need to
invoke the super class’s constructor using “super()” as

Example
Following java program demonstrates how to call a super class’s
constructor from the constructor of the sub class using the super
keyword.
class Person{
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String branch;
public int Student_id;
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Branch: "+this.branch);
System.out.println("Student ID: "+this.Student_id);
}
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Student("Krishna", 20, "IT", 1256);
person.displayPerson();
}
}

Output
Data of the Person class:
Name: Krishna
Age: 20

Creating a Multilevel Hierarchy


Inheritance involves an object acquiring the properties and behaviour of
another object. So basically, using inheritance can extend the
functionality of the class by creating a new class that builds on the
previous class by inheriting it.
Multilevel inheritance is when a class inherits a class which inherits
another class. An example of this is class C inherits class B and class B in
turn inherits class A.
A program that demonstrates a multilevel inheritance hierarchy in Java is
given as follows:

Example
class A {
void funcA() {
System.out.println("This is class A");
}
}
class B extends A {
void funcB() {
System.out.println("This is class B");
}
}
class C extends B {
void funcC() {
System.out.println("This is class C");
}
}
public class Demo {
public static void main(String args[]) {
C obj = new C();
obj.funcA();
obj.funcB();
obj.funcC();
}
}

Output
This is class A
This is class B
This is class C

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It
can have abstract and non-abstract methods. It needs to be extended and
its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the
body of the method.

Example of abstract class


1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have
implementation is known as an abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract


method
In this example, Bike is an abstract class that contains only one abstract
method run. Its implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda();
8. obj.run();
9. }
10.}
running safely

final keyword
final keyword is used in different contexts. First of all, final is a non-access
modifier applicable only to a variable, a method, or a class. The following are
different contexts where final is used.
1. class Bike{
2. final int speedlimit;//blank final variable
3.
4. Bike(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike();
11. }
12.}
Output: 70

Object Class in Java


Object class is present in java.lang package. Every class in Java is
directly or indirectly derived from the Object class. If a class does
not extend any other class then it is a direct child class
of Object and if extends another class then it is indirectly derived.
Therefore the Object class methods are available to all Java classes.
Hence Object class acts as a root of the inheritance hierarchy in any
Java Program.
Using Object Class Methods
The Object class provides multiple methods which are as follows:
 tostring() method
 hashCode() method
 equals(Object obj) method
 finalize() method
 getClass() method
 clone() method
 wait(), notify() notifyAll() methods

// Java program to demonstrate working of finalize()

public class Test {


public static void main(String[] args)
{
Test t = new Test();
System.out.println(t.hashCode());

t = null;

// calling garbage collector


System.gc();

System.out.println("end");
}
@Override protected void finalize()
{
System.out.println("finalize method called");
}
}

Output:
366712642
finalize method called
end

You might also like