0% found this document useful (0 votes)
4 views25 pages

403-Java-Unit-2

Uploaded by

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

403-Java-Unit-2

Uploaded by

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

403 - Java Programming Language

Unit 2 Classes and Objects

2.1 Simple Class, Field

A class in Java is a template for creating objects. A class in Java is a set of objects which shares common
characteristics and common properties. It is a user-defined blueprint or prototype from which objects
are created. For example, a Student is a class while a particular student named Ravi is an object.
Properties of Java Classes

• Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.
• Class does not occupy memory.
• Class is a group of variables of different data types and a group of methods.
• A Class in Java can contain:
o Data member
o Method
o Constructor
o Nested Class
o Interface

Syntax
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;
}

Components of Java Classes

In general, class declarations can include these components, in order:

Modifiers: A class can be public or has default access (Refer this for details).

Class keyword: Class keyword is used to create a class.

Class name: The name should begin with an initial letter (capitalized by convention).

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.

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.

Body: The class body is surrounded by braces, { }.

Instance Variable in Java

1|C. B. Patel Computer College


403 - Java Programming Language

A variable created inside the class but outside the method is known as an instance variable. An instance
variable does not get memory at compile time; it gets memory at runtime when an object or instance
is created. Each class instance has its copy of instance variables, which means that changes made to
instance variables of one object do not affect the values of instance variables in other objects of the
same class. Moreover, setter methods and constructors can be used to initialize them. In object-
oriented programming, instance variables are crucial for encapsulating data within objects since they
are frequently used to represent the state or properties of objects.

Method in Java

In Java method is a block of code inside a class that is intended to carry out a certain function. To
provide a mechanism to interact with the state of an object and to encapsulate behavior within
objects, methods are required.

2.2 Object Creation

An object is a real-world entity that has state and behaviour. In other words, an object is a tangible
thing that can be touch and feel, like a car or chair, etc. are the example of objects. The banking system
is an example of an intangible object. Every object has a distinct identity, which is usually implemented
by a unique ID that the JVM uses internally for identification.

Characteristics of an Object:

• State: It represents the data (value) of an object.


• Behavior: It represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
• Identity: An object's identity is typically implemented via a unique ID. The ID's value is not
visible to the external user; however, it is used internally by the JVM to identify each object
uniquely.

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to
write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are created.
So, an object is the instance(result) of a class.

Object Definitions:
o An object is a real-world entity.
o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in the Heap memory
area. In Java, an instance of a class-also referred to as an object-is created using the new keyword. The

2|C. B. Patel Computer College


403 - Java Programming Language

new keyword dynamically allocates memory for an object of that class and returns a reference to it
when it is followed by the class name and brackets with optional arguments.

Example

// Java Class example


class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String n;
public static void main(String args[])
{
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.n);
}
}

2.2 Access Modifiers in Java

In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc. to the user depending upon the access modifier used
with the element. In this article, let us learn about Java Access Modifiers, their types, and the uses of
access modifiers.

Types of Access Modifiers

There are 4 types of access modifiers available in Java:

1. Default Access Modifier

When no access modifier is specified for a class, method, or data member, it is said to be having the
default access modifier by default. The default access modifiers are accessible only within the same
package. It provides more accessibility than private. But, it is more restrictive than protected, and
public.

class Log {
void display() {
System.out.println("Displaying log information");
}
}

In this example, the Log class and its method display() are accessible only within classes defined in the
same package.

2. Private Access modifier

3|C. B. Patel Computer College


403 - Java Programming Language

The private access modifier is the most restrictive level of access control. When a member (be it a field,
method, or constructor) is declared private, it can only be accessed within the same class. No other
class, including subclasses in the same package or different packages, can access the member. This
modifier is typically used for sensitive data that should be hidden from external classes.

Example:

public class Person {


private String name;
private String getName() {
return this.name;
}
}

In this example, the name attribute and the getName() method are only accessible within the Person
class.

3. Protected Access modifier

The protected access modifier is less restrictive than private and default. Members declared as
protected can be accessed within the same package or in subclasses in different packages. This is
particularly useful in cases where you want to hide a member from the world but still make it available
to child classes.

Example:

public class Animal {


protected String type;
protected void displayType() {
System.out.println("Type: " + type);
}
}

Here, the type attribute and the displayType() method can be accessed within all classes in the same
package and in any subclass of Animal, even if those subclasses are in different packages.

4. Public Access modifier

The public access modifier is the least restrictive and specifies that the member can be accessed from
any other class anywhere, whether within or in a different package. This access level is typically used
for methods and variables that must be available consistently to all other classes.

Example:

public class Calculator {


public int add(int num1, int num2) {
return num1 + num2;

4|C. B. Patel Computer College


403 - Java Programming Language

}
}

In this example, the add() method of the Calculator class can be accessed by any other class.

2.3 Construction and initialization

In Java, a Constructor is a block of codes like the method. It is called when an instance of the class is
created. At the time of calling the constructor, memory for the object is allocated in the memory. It is
a special type of method that is used to initialize the object. Every time an object is created using the
new() keyword, at least one constructor is called.

Rules for Creating Java Constructor

There are following rules for defining a constructor:

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


• A Constructor must have no explicit return type.
• 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)

A constructor is called "Default Constructor" when it does not have any parameter

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

5|C. B. Patel Computer College


403 - Java Programming Language

2. Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor. The
parameterized constructor is used to provide different values to distinct objects.

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();
}
}
2.4 Inheritance

Inheritance is a mechanism of driving a new class from an existing class. The existing (old) class is
known as base class or super class or parent class. The new class is known as a derived class or sub
class or child class. It allows us to use the properties and behavior of one class (parent) in another class
(child).

Why Do We Need Java Inheritance?

Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can
directly use the parent class code.

Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways
by which Java achieves Run Time Polymorphism.

Abstraction: The concept of abstract where we do not have to provide all details, is achieved through
inheritance. Abstraction only shows the functionality to the user.

Important Terminologies Used in Java Inheritance

6|C. B. Patel Computer College


403 - Java Programming Language

Class: Class is a set of objects which shares common characteristics/ behavior and common properties/
attributes. Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.

Super Class/Parent Class: The class whose features are inherited is known as a superclass(or a base
class or a parent class).

Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and methods in addition to the
superclass fields and methods.

Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.

The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are
derived from an existing class. In other words, “extends” refers to increased functionality.

Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}

Types of Inheritance

1. Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below
figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’ inherits all the properties of the class ‘A’.

class Employee
{
float salary=34534*12;
}
public class Executive extends Employee

7|C. B. Patel Computer College


403 - Java Programming Language

{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}

2. multilevel Inheritance

In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class
also acts as the base class for other classes. In the below image, class A serves as a base class for the
derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot
directly access the grandparent’s members.

//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}

8|C. B. Patel Computer College


403 - Java Programming Language

void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}

3. Hierarchical Inheritance

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

//parent class
class Student

9|C. B. Patel Computer College


403 - Java Programming Language

{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}

4. Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance involving multiple inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only through Interfaces if we want to involve
multiple inheritance to implement Hybrid inheritance. However, it is important to note that Hybrid
inheritance does not necessarily require the use of Multiple Inheritance exclusively. It can be achieved
through a combination of Multilevel Inheritance and Hierarchical Inheritance with classes, Hierarchical

10 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

and Single Inheritance with classes. Therefore, it is indeed possible to implement Hybrid inheritance
using classes alone, without relying on multiple inheritance type.

//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}

5. Multiple Inheritance (not supported)

Java does not support multiple inheritances due to ambiguity. For example, consider the following Java
program.

2.4.1 Data Encapsulation

Encapsulation in Java is a process of wrapping code and data together into a single unit. t provides you
the control over the data. It is a way to achieve data hiding in Java because other class will not be able
to access the data through the private data members. Encapsulation is defined as the wrapping up of

11 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

data under a single unit. It is the mechanism that binds together code and the data it manipulates.
Another way to think about encapsulation is, that it is a protective shield that prevents the data from
being accessed by the code outside this shield. In encapsulation, the variables or data of a class are
hidden from any other class and can be accessed only through any member function of its own class.
A private class can hide its members or methods from the end user, using abstraction to hide
implementation details, by combining data hiding and abstraction. Encapsulation can be achieved by
Declaring all the variables in the class as private and writing public methods in the class to set and get
the values of variables. It is more defined with the setter and getter method.

Example:

// Java program to demonstrate the Encapsulation.


class Person {
// Encapsulating the name and age
// only approachable and used using
// methods defined
private String name;
private int age;

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public int getAge() { return age; }

public void setAge(int age) { this.age = age; }


}

// Driver Class
public class test_encap {
// main function
public static void main(String[] args)
{
// person object created
Person p = new Person();
p.setName("John");
p.setAge(30);
// Using methods to get the values from the
// variables
System.out.println("Name: " + p.getName());
System.out.println("Age: " + p.getAge());
}
}

2.4.1 Overloading

Method overloading in Java is also known as Compile-time Polymorphism, Static Polymorphism, or


Early binding. In Method overloading compared to the parent argument, the child argument will get
the highest priority. Method overloading in Java is the feature that enables defining several methods
in a class having the same name but with different parameters lists. These algorithms may vary with

12 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

regard to the number or type of parameters. When a method is called, Java decides which version of
it to execute depending on the arguments given. If we have to perform only one operation, having the
same name of the methods increases the readability of the program. Suppose you have to perform
the 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.

Different Ways of Method Overloading in Java

• Changing the Number of Parameters.


• Changing Data Types of the Arguments.
• Changing the Order of the Parameters of Methods

// Java program to demonstrate working of method overloading in Java

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

2.4.1 Overriding

Overriding in Java occurs when a subclass implements a method which is already defined in the
superclass or Base Class. The method in the subclass must have the same signature as in the superclass.
It allows the subclass to modify the inherited methods. 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

13 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

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

• Method overriding is used to provide the specific implementation of a method that is already
provided by its superclass.
• Method overriding is used for runtime polymorphism.
• Method overriding allows subclasses to reuse and build upon the functionality provided by
their superclass, reducing redundancy and promoting modular code design.
• Subclasses can override methods to tailor them to their specific needs or to implement
specialized behavior that is unique to the subclass.
• Method overriding enables dynamic method dispatch, where the actual method
implementation to be executed is determined at runtime based on the type of object,
supporting flexibility and polymorphic behavior.

Rules for Java Method Overriding

• Same Method Name: The overriding method in the subclass must have the same name as the
method in the superclass that it is overriding.
• Same Parameters: The overriding method must have the same number and types of
parameters as the method in the superclass. This ensures compatibility and consistency with
the method signature defined in the superclass.
• IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship between the
subclass and the superclass. This means that the subclass must inherit from the superclass,
either directly or indirectly, to override its methods.
• Same Return Type or Covariant Return Type: The return type of the overriding method can be
the same as the return type of the overridden method in the superclass, or it can be a subtype
of the return type in the superclass. This is known as the covariant return type, introduced in
Java 5.
• Access Modifier Restrictions: The access modifier of the overriding method must be the same
as or less restrictive than the access modifier of the overridden method in the superclass.
Specifically, a method declared as public in the superclass can be overridden as public or
protected but not as private. Similarly, a method declared as protected in the superclass can
be overridden as protected or public but not as private. A method declared as default
(package-private) in the superclass can be overridden with default, protected, or public, but
not as private.
• No Final Methods: Methods declared as final in the superclass cannot be overridden in the
subclass. This is because final methods cannot be modified or extended.
• No Static Methods: Static methods in Java are resolved at compile time and cannot be
overridden. Instead, they are hidden in the subclass if a method with the same signature is
defined in the subclass.

// Example of Overriding in Java


class Animal {
// Base class

14 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

void move() { System.out.println(


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

class Dog extends Animal {


void move()
{ // move method from Base class is overriden in this
// method
System.out.println("Dog is running.");
}
void bark() { System.out.println("Dog is barking."); }
}

public class Geeks {


public static void main(String[] args)
{
Dog d = new Dog();
d.move(); // Output: Dog is running.
d.eat(); // Output: Animal is eating.
d.bark(); // Output: Dog is barking.
}
}

2.5 This and Super Keyword

This keyword

In java, super keyword is used to access methods of the parent class while this is used to access
methods of the current class.

this keyword is a reserved keyword in java i.e, we can’t use it as an identifier. It is used to refer current
class’s instance as well as static members. It can be used in various contexts as given below:

• to refer instance variable of current class


• to invoke or initiate current class constructor
• can be passed as an argument in the method call
• can be passed as argument in the constructor call
• can be used to return the current class instance

// Program to illustrate this keyword is used to refer current class


class RR {
// instance variable
int a = 10;

// static variable
static int b = 20;

void fun()
{

15 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

// referring current class(i.e, class RR)


// instance variable(i.e, a)
this.a = 100;

System.out.println(a);

// referring current class(i.e, class RR)


// static variable(i.e, b)
this.b = 600;

System.out.println(b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().fun();
}
}

Super keyword

• super is a reserved keyword in java i.e, we can’t use it as an identifier.


• super is used to refer super-class’s instance as well as static members.
• super is also used to invoke super-class’s method or constructor.
• super keyword in java programming language refers to the superclass of the class where the
super keyword is currently being used.
• The most common use of super keyword is that it eliminates the confusion between the
superclasses and subclasses that have methods with same name.

super can be used in various contexts as given below:

• it can be used to refer immediate parent class instance variable


• it can be used to refer immediate parent class method
• it can be used to refer immediate parent class constructor.

// Program to illustrate super keyword refers super-class instance

class Parent {
// instance variable
int a = 10;

// static variable
static int b = 20;
}

16 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

class Base extends Parent {


void rr()
{
// referring parent class(i.e, class Parent)
// instance variable(i.e, a)
System.out.println(super.a);

// referring parent class(i.e, class Parent)


// static variable(i.e, b)
System.out.println(super.b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use 'super'
// in static context.
// super.a = 700;
new Base().rr();
}
}

Difference Between this and super keyword

2.4 Polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.

Advantages of Polymorphism

1. Code Reusability: Polymorphism allows methods in subclasses to override methods in their


superclass, enabling code reuse and maintaining a consistent interface across related classes.

17 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

2. Flexibility and Extensibility: Polymorphism allows subclasses to provide their own implementations
of methods defined in the superclass, making it easier to extend and customize behavior without
modifying existing code.

3. Dynamic Method Invocation: Polymorphism enables dynamic method invocation, where the
method called is determined by the actual object type at runtime, providing flexibility in method
dispatch.

4. Interface Implementation: Interfaces in Java allow multiple classes to implement the same interface
with their own implementations, facilitating polymorphic behavior and enabling objects of different
classes to be treated interchangeably based on a common interface.

5. Method Overloading: Polymorphism is also achieved through method overloading, where multiple
methods with the same name but different parameter lists can be defined within a class or its
subclasses, enhancing code readability and allowing flexibility in method invocation based on
parameter types.

6. Reduced Code Complexity: Polymorphism helps reduce code complexity by promoting a modular
and hierarchical class structure, making it easier to understand, maintain, and extend large-scale
software systems.

Types of Polymorphism

There are two types of polymorphism in Java: We can perform polymorphism in Java by method
overloading and method overriding.

1. Compile- Time Polymorphism in Java

In Java, method overloading is used to achieve compile-time polymorphism. A class can have
numerous methods with the same name but distinct parameter lists thanks to method overloading.
The compiler uses the amount and kind of parameters provided to it during compilation to decide
which method to call. This choice is made during compilation, which is why it's called "compile-time
polymorphism." The methods in method overloading must have the same name but differ in the
quantity or kind of parameters. Based on the inputs passed in during the method call, the compiler
chooses the suitable overloaded method when a method is called. In the event of a perfect match,
that procedure is used. If not, the compiler uses broadening to find the closest match depending on
the parameter types

Run- Time Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time. In this process, an overridden method is
called through the reference variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable. This type of polymorphism is achieved
by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a
definition for one of the member functions of the base class. That base function is said to be
overridden.

18 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

1.6 Static members, Static Block. Static Class

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:

• Variable (also known as a class variable)


• Method (also known as a class method)
• Block
• Nested class

Beyond memory management, the static keyword in Java has several other uses. When it comes to
variables, it means that the variable is shared by all instances of the class and belongs to the class as
a whole, not just any one instance. Static methods are available throughout the programme since they
can be called without first generating an instance of the class. When the class loads, static blocks are
used to initialise static variables or carry out one-time operations. Furthermore, nested static classes
can be instantiated individually but are still linked to the outer class. Moreover, class names can be
used to access static variables and methods directly, eliminating the need to build an object instance.
This is especially helpful for constants or utility methods.

Java static variable

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

• 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.
• The static variable gets memory only once in the class area at the time of class loading.
• Static variables in Java are also initialized to default values if not explicitly initialized by the
programmer. They can be accessed directly using the class name without needing to create
an instance of the class.
• Static variables are shared among all instances of the class, meaning if the value of a static
variable is changed in one instance, it will reflect the change in all other instances as well.

//Java Program to illustrate the use of static variable which


//is shared with all objects.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}

public static void main(String args[]){


//creating objects
Counter2 c1=new Counter2();

19 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

Counter2 c2=new Counter2();


Counter2 c3=new Counter2();
}
}

Java Static Method

If we apply a static keyword with any method, it is known as a static method.

• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data members and can change their value of it.

//Java Program to demonstrate the use of a static method.


class Student{
int rollno;
String name;
static String college = "CBPCC";
//static method to change the value of static variable
static void change(){
college = "C. B. PATEL COMPUTER COLLEGE";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

Java Static Block

It is used to initialize the static data member. It is executed before the main() method at the time of
class loading.

// Java program to demonstrate use of static blocks

20 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}

Java Static Classes

A class can be made static only if it is a nested class. We cannot declare a top-level class with a static
modifier but can declare nested classes as static. Such types of classes are called Nested static
classes. Nested static class doesn’t need a reference of Outer class. In this case, a static class cannot
access non-static members of the Outer class.

// A java program to demonstrate use of static keyword with Classes

import java.io.*;

public class test {

private static String str = "bca";

// Static class
static class MyNestedClass {

// non-static method
public void disp(){
System.out.println(str);
}
}

public static void main(String args[])


{
test.MyNestedClass obj
= new test.MyNestedClass();
obj.disp();
}
}

21 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

2.7 Interfaces

An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static
constants and abstract methods.

• The interface in Java is a mechanism to achieve abstraction.


• By default, variables in an interface are public, static, and final.
• It is used to achieve abstraction and multiple inheritances in Java.
• It is also used to achieve loose coupling.
• In other words, interfaces primarily define methods that other classes must implement

interface Animal {
public void eat();
public void travel();
}

Implementing Interfaces in Java

When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.A class uses the implements keyword to
implement an interface. The implements keyword appears in the class declaration following the
extends portion of the declaration.

public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Multiple Inheritance in Java Using Interface

Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But we can
use multiple inheritances in Java using Interface. Let us check this with an example.

22 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

import java.io.*;

// Add interface
interface Add{
int add(int a,int b);
}

// Sub interface
interface Sub{
int sub(int a,int b);
}

// Calculator class implementing


// Add and Sub
class Cal implements Add , Sub
{
// Method to add two numbers
public int add(int a,int b){
return a+b;
}

// Method to sub two numbers


public int sub(int a,int b){
return a-b;
}

class test{
// Main Method
public static void main (String[] args)
{
// instance of Cal class
Cal x = new Cal();

System.out.println("Addition : " + x.add(2,1));


System.out.println("Substraction : " + x.sub(2,1));

}
}

Using extends and implements together

We can also extend a class and implement an interface, but the rule is to always extend first and
then implement.

class Animal {
void move() {
System.out.println("This animal moves.");
}

23 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

interface Pet {
void play();
}

class Dog extends Animal implements Pet {


void bark() {
System.out.println("The dog barks.");
}

public void play() {


System.out.println("The dog plays.");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.move(); // Inherited method from Animal
dog.bark(); // Method of Dog class
dog.play(); // Implemented method from Pet interface
}
}
Difference between class and interface

24 | C . B . P a t e l C o m p u t e r C o l l e g e
403 - Java Programming Language

25 | C . B . P a t e l C o m p u t e r C o l l e g e

You might also like