You are on page 1of 42

UNIT III

 Class
A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical. It represents the
set of properties or methods that are common to all objects of one type.

A class is a template used to create objects. Classes are made up of members, the main
two of which are fields and methods. Fields are variables that hold the state of the object,
whereas methods define what the object can do—the so-called behaviors of the object.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

class <class_name>{
field;
method;
}

Example

class MyRectangle

int x, y;
int getArea()

return x * y;

 Object
It is a basic unit of Object-Oriented Programming and represents the real life entities.
Object Creation

To access a (non-static) field or method from outside the defining class, an object of the
class must first be created. That’s done using the new keyword, which will create a new
object in the system’s memory.

Syntax

Classname object = new Classname();

Example

public class MyApp

public static void main(String[] args)

{ // Create an object of MyRectangle MyRectangle r = new MyRectangle();

}
An object is also called an instance. The object will contain its own set of instance
variables (non-static fields), which can hold values that are different from those of other
instances of the class.

Accessing Object Members

In addition to creating the object, the members of the class that are to be accessible
beyond their package need to be declared as public in the class definition.

class MyRectangle

public int x, y; public int getArea()

return x * y;

The members of this object can now be reached by using the dot operator after the
instance name:

public class MyApp

{ public static void main(String[] args)

MyRectangle r = new MyRectangle();

r.x = 10;

r.y = 5;

int area = r.getArea(); // 50 (5*10)

}
 Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object
is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class

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(argument list)
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>()
{

Example:
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.

class Student3{
int id;
String name;
.//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Java Parameterized Constructor

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


constructor.

Example

class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Constructor Overloading
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.

Constructor overloading is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and
their types.

Example of Constructor Overloading

//Java program to overload constructors


class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Difference between constructor and method in Java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default The method is not provided by the compiler
constructor if you don't have any constructor in any case.
in a class.

The constructor name must be same as the The method name may or may not be same
class name. as the class name.
 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.
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.

There are many ways to unreferenced the object:

ch

o By nulling the reference


o By assigning a reference to another
o By anonymous object etc.
1) By nulling a reference:

1. mployee e=new Employee();


2. e=null;

2) By assigning a reference to another:

1. Employee e1=new Employee();


2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:

1. new Employee();

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(){}

1. public class TestGarbage1{


2. public void finalize(){System.out.println("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. System.gc();
9. }
10. }
 Methods
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.

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.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
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.

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 Declaration

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.

Example:
void myPrint()

System.out.println("Hello");

Calling Methods
The preceding method will simply print out a text message. To invoke (call) it from the
main method, an instance of the MyApp class must be created first. The dot operator is
then used after the instance’s name in order to access its members, which include the
myPrint method.
public static void main(String[] args)

MyApp m = new MyApp();

m.myPrint(); // "Hello"

Method Parameters
The parentheses that follow the method name are used to pass arguments to the method.
To do that, the corresponding parameters must first be added to the method declaration in
the form of a comma-separated list.

void myPrint(String s)

System.out.println(s);

A method can be defined to take any number of arguments, and they can have any data
types. Just ensure that the method is called with the same types and number of arguments
in the correct order.

public static void main(String[] args)

MyApp m = new MyApp();

m.myPrint("Hello"); // "Hello"

Return Statement
A method can return a value. The void keyword is then replaced with the data type the
method will return, and the return keyword is added to the method body with an
argument of the specified return type.
public class MyApp {

String getString()

return "Hello";

Return is a jump statement that causes the method to exit and return the specified value to
the place where the method was called. For example, the preceding method can be passed
as an argument to the println method because the method evaluates to a string.

public static void main(String[] args)

MyApp m = new MyApp();

System.out.println( m.getString() ); // "Hello"

Example:

class Addition {

int sum = 0;

public int addTwoInt(int a, int b){

// adding two integer value.


sum = a + b;

//returning summation of two values.


return sum;
}

}
class GFG {
public static void main (String[] args) {

// creating an instance of Addition class


Addition add = new Addition();

// calling addTwoInt() method to add two integer using instance created


// in above step.
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);

}
}

Example:

import java.util.Scanner;
public class EvenOdd
{
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
}

Example:

public class Addition


{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}

Method Overloading
It’s possible to declare multiple methods with the same name as long as the parameters
vary in type or number. Called method overloading,
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

1) 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.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

2) Method Overloading: changing data type of arguments

class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Static Method
A method that has static keyword is known as static method. In other words, a method
that belongs to a class rather than an instance of a class is known as a static method. We
can also create a static method by using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It
can access static data members and also change the value of it. It is used to create an
instance method. It is invoked by using the class name.

Example of static method

Display.java

public class Display


{
static void show()
{
System.out.println("It is an example of static method.");
}

public static void main(String[] args)


{
show();
}
}

Example
class MyCircle

float r = 10; // instance field

static float pi = 3.14F; // staticclass field

float getArea() // Instance method

return newArea(r);

static float newArea(float a) // Static class method

return pi*a*a;

public static void main(String[] args)

float f = MyCircle.pi;

MyCircle c = new MyCircle();


float g = c.r;

There are 2 ways that any computer language can pass an argument to a
subroutine.

Call by value:

Call by reference

1. Call by value: This method copies the value of an argument into a formal
parameter of the subroutine. Therefore, changes made to the parameter of the
subroutine have no effect on the argument used to call it.

In java when you pass a simple type of method, it is passed by value. Thus , what occurs
to the parameter that receive the argument has no effect outside the method.

class Operation{
int data=50;

void change(int data){


data=data+100;//changes will be in the local variable only
}

public static void main(String args[]){


Operation op=new Operation();

System.out.println("before change "+op.data);


op.change(500);
System.out.println("after change "+op.data);

}
}
2. Call by reference: A reference to an argument (not the value of the argument) is
passed to the parameter. Inside the subroutine, this reference is used to access the actual
argument specified in the call. This means that changes made to the parameter will
affected the argument used to call the subroutine.

In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value. Let's take a simple example:

class Operation2{
int data=50;

void change(Operation2 op){


op.data=op.data+100;//changes will be in the instance variable
}

public static void main(String args[]){


Operation2 op=new Operation2();

System.out.println("before change "+op.data);


op.change(op);//passing object
System.out.println("after change "+op.data);

}
}

Inheritance
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 (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new class 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 overriding so that runtime-polymorphism in java can be achieved.


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.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java:

 single

 multilevel

 hierarchical
Types of Inheritance
There are various types of inheritance as demonstrated below.

Single Inheritance

When a class inherits another class, it is known as a single inheritance.

Example:

class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
public class Tester {
public static void main(String[] arguments) {
Rectangle rect = new Rectangle();
rect.display();
rect.area();
}
}

Multilevel Inheritance

In Multi-Level Inheritance in Java, a class extends to another class that is already


extended from another class. For example, if there is a class A that extends class B and
class B extends from another class C, then this scenario is known to follow Multi-level
Inheritance.

Example:

class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}

Hierarchical Inheritance

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.In below image, the class A serves as a base class for the derived class B,C
and D.
Example:

class Shape{

void calculateArea(int a,int b){

System.out.println("Area = "+(a*b));

void calculatePerimeter(int a, int b){

int p = 2 * (a+b);

System.out.println("Permeter = "+p);

class Area extends Shape{


int a,b;

Area(){

a= 10;

b=20;

calculateArea(a,b);

class Perimeter extends Shape{

int a,b;

Perimeter(){

a = 5;

b= 6;

calculatePerimeter(a,b);

class Main{

public static void main(String args[]){

Area a = new Area();

Perimeter p = new Perimeter();

 Visibility Control
It is possible to inherit all the members of a class by a subclass using keyword extends.
The methods and variables in the class are visible everywhere in the program. However,
it may be necessary to restrict the access to certain variables and methods from outside
the class. We can achieve this in java by applying visibility modifiers to the instance
variables and methods. The visibility modifiers are also known as access modifiers. Java
provides three types of visibility modifiers:

 public
 protected
 private

public access:

Any variable or method is visible to the entire class in which it is defines

Example:

public int x;
public void sum(){}

protected access:

the protected modifier makes the fields visible not only to all classes and subclasses in
the same package but also to subclass in the other packages.

private access:

private fields enjoy the highest level degree of protection. They are accessible only with
their own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. A method declared as private behaves like a method declared as final. It
prevents the method from being subclassed.

 Super keyword
super keyword is used to refer base class. It can be used for two purposes:

i) To invoke base constructor


Whenever we have a parameterized constructor in base class it cannot be invoked by
its own when child object is created, then we can use super keyword in the child
constructor to invoke it.
The super keyword statement should be the first statement of child constructor.
ii) To invoke base class method
Whenever we have methods with same signature in base and child class then we can
invoke base class method using super keyword
Syntax:
super.methodname(arguments list);

Example:
class A{
public A(String a){
System.out.println(“Base class constructor ”+ a);
}
public void show(){
System.out.println(“Base class method”);
}
}
class B extends A{
public B(String s1){
super(“Object”);
System.out.println(“Sub class constructor ”+s1);
}
public void show(){
super.show();
System.out.println(“Base class method”);
}
}
class superex
{
public static void main(String arg[]){
B ob = new B(“Child Object”); //creating child class object
ob.show();
}
}

 Overriding method
The methods defined in super class is inherited by its subclass and is used by the objects
created by the subclass. Method inheritance enables us to define and use methods
repeatedly in subclasses without having to define the method again in subclass.

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method


which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example:

class Super{
int x;
Super(int x){
This.x = x;
}
void display(){
System.out.println(“Super x = ”+x);
}
}
class Sub extends Super{
int y;
Sub(int x,int y){
super(x);
this.y = y;
}
void display(){
super.display();
System.out.println(“Sub y = ”+y);
}
}
class Super{
public static void main(String arg[]){
Sub ob = new Sub(100,200);
ob.display();
}
}

Dynamic method dispatch

Dynamic method dispatch is an important mechanism in Java that is used to


implement runtime polymorphism. In this mechanism, method overriding is resolved
at runtime instead of compile time. That means the choice of the version of the
overridden method to be executed in response to a method call is done at runtime.

Example:
class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}
}

class BabyDog1 extends Dog{


public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}}

 Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body). It needs to be
extended and its method implemented. It cannot be instantiated.

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Following are some important observations about abstract classes in Java.


1. An object (instance) of an abstract class cannot be created.
2. Constructors are allowed.
3. We can have abstract class without any abstract method.
4. Abstract classes can also have final methods
5. We are not allowed to create object for any abstract class.
6. We can define static methods in an abstract class

Syntax of abstract class

abstract class A{}


Example
abstract class Shape {
int color;

// An abstract function
abstract void draw();
}

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

Example of abstract method

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

Example

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

Example

abstract class Shape{


abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g.,getSh
ape() method
s.draw();
}
}

 Final Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable.

final variable

If you make any variable as final, you cannot change the value of final variable. In other
words when a variable is declared with final keyword, its value can’t be modified,
essentially, a constant.

Example

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Output: Compile time error

final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. The Object class does this—a number of its methods are
final. We must declare methods with the final keyword for which we are required to
follow the same implementation throughout all the derived classes.

Example

class Bike{

final void run(){System.out.println("running");}


}

class Honda extends Bike{


void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}

Output: Compile time error


final class

When a class is declared with final keyword, it is called a final class. A final class
cannot be extended(inherited).

There are two uses of a final class:


Usage 1: One is definitely to prevent inheritance, as final classes cannot be extended.
For example, all wrapper class like Integer, Float etc, etc. are final classes. We cannot
extend them.

final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}

Usage 2: The other use of final with classes is to create an immutable class like the
predefined String class. One cannot make a class immutable without making it final.

Example for final class

final class Bike{}

class Honda1 extends Bike{


void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile time error

You might also like