[Go to site: main page, start]

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

Java Notes Unit 2

The document covers the fundamentals of Object-Oriented Programming (OOP) in Java, focusing on classes and objects, including definitions, syntax, and examples of class creation, object instantiation, and method declarations. It explains constructors, including default, parameterized, and copy constructors, as well as concepts like constructor overloading and method overloading. Additionally, it introduces static members and recursion in Java programming.

Uploaded by

yashuyy75
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 views57 pages

Java Notes Unit 2

The document covers the fundamentals of Object-Oriented Programming (OOP) in Java, focusing on classes and objects, including definitions, syntax, and examples of class creation, object instantiation, and method declarations. It explains constructors, including default, parameterized, and copy constructors, as well as concepts like constructor overloading and method overloading. Additionally, it introduces static members and recursion in Java programming.

Uploaded by

yashuyy75
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

OBJECT ORIENETED PROGRAMMING WITH JAVA

UNIT - 2
CLASSES AND OBJECTS
Introduction

Java is a true object-oriented language and therefore the underlying structure of all Java programs is
classes. Anything we wish to represent in a Java program must be encapsulated in a class that defines the
state and behavior of the basic program components known as objects. Classes create objects and objects
use methods to communicate between them.
In Java, the data items are called fields and the functions are called methods. How they are used to build
a Java program that incorporates the basic OOP concepts such as encapsulation, inheritance and
polymorphism.
Defining a Class:
A class is a user-defined datatype which has its own data members and member functions. In Java, the
data items are called fields and the functions are called methods. A class is a blue print with a template
that serves to define its properties.
A Class in Java can contain:
➢ Data member
➢ Method
➢ Constructor
➢ Nested Class
➢ Interface
Class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must 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 surrounded by braces, { }.

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 1


OBJECT ORIENETED PROGRAMMING WITH JAVA

Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}

Example:

public class Simple


{
public static void main(String args[])
{
[Link]("Hello Java");
}
}

Adding Variables:
Data is encapsulated in a class by placing data fields inside the body of the class definition. These
variables are called instance variables because they are created whenever an object of the class is
instantiated.
Example:
class Rectangle
{
int length;
int width;
}
Methods Declaration:
A class with only data fields (and without methods that operate on that data) has no life. The objects
created by such a class cannot respond to any messages. We must therefore add methods that are necessary
for manipulating the data contained in the class. Methods are declared inside the body of the class but
immediately after the declaration of instance variables.

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 2


OBJECT ORIENETED PROGRAMMING WITH JAVA

The general form of a method declaration is:


returntype methodname (parameter-list)
{
// method body;
}
Method declarations have four basic parts:
• The name of the method (methodname)
• The type of the value the method returns
• A list of parameters (parameter-list)
• The body of the method
The type specifies the type of value the method would return. The methodname is valid identifiers. The
parameter list is always enclosed in parentheses, separated by comma.
Examples:
void getdata(int a, float b, double c)
{
// Method body
}
Creating Objects:
Objects: Objects are the basic runtime entities which has state and behavior. Creating an object is also
referred to as instantiating an object. Objects in Java are created using the new operator.

Syntax:
Class_name object_name = new Class_name( );
Accessing Objects:
All variables must be assigned values before they are used. To access class members outside the class,
the instance variables and the methods cannot be accessed directly. To use the concerned object and
the dot operator as shown below:
[Link];
[Link](Parameter-list);

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 3


OBJECT ORIENETED PROGRAMMING WITH JAVA

Example Program to use class, Creating and accesing the objects.


class Student
{
String name;
int age;

void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

public class Main


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

Student s = new Student(); // Creating object

[Link] = "Radha"; // Assigning values


[Link] = 20;

[Link](); // Calling method


}

OUTPUT:
Name: Radha
Age: 20

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 4


OBJECT ORIENETED PROGRAMMING WITH JAVA

Constructors
A constructor is a special method that is used to initialize an object.. A constructor does not have any
return type even void type.
A constructor has same name as the class in which it resides. Constructor in Java cannot be abstract,
static, final or synchronized. These modifiers are not allowed for constructor.

Types of Constructors in Java


1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor

1. Default Constructor:
A default constructor is a constructor that does not take any parameters. It initializes the object with
default values.

Example:
class Student
{
String name;
int age;

// Default Constructor
Student()
{
name = "Mohan";
age = 20;
}
void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 5


OBJECT ORIENETED PROGRAMMING WITH JAVA

public class Main


{
public static void main(String[] args)
{
Student s = new Student();
[Link]();
}
}

OUTPUT:
Name:Mohan
Age: 20

2. Parameterized Constructor
A parameterized constructor is a constructor that accepts arguments. It is used to initialize data members
with user-defined values.

Example:
class Student
{
String name;
int age;

// Parameterized Constructor
Student(String n, int a)
{
name = n;
age = a;
}

void display()
{

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 6


OBJECT ORIENETED PROGRAMMING WITH JAVA

[Link]("Name: " + name);


[Link]("Age: " + age);
}
}

public class Main


{
public static void main(String[] args) {
Student s = new Student("Mohan", 22);
[Link]();
}
}
OUTPUT:
Name:Mohan
Age: 22

3. Copy Constructor:
A copy constructor is a constructor that creates a new object by copying the values of another object of
the same class.

The syntax for a copy constructor in Java is as follows:


ClassName(ClassName objectName)
{
// Copy the fields from objectName to the new object
}
Example:
class Student
{
String name;
int age;

Student(String n, int a)

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 7


OBJECT ORIENETED PROGRAMMING WITH JAVA

{
name = n;
age = a;
}

// Copy Constructor
Student(Student s)
{
name = [Link];
age = [Link];
}

void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
public class Main
{
public static void main(String[] args)
{
Student s1 = new Student("Radha ", 21);
Student s2 = new Student(s1);

[Link]();
}
}
OUTPUT:
Name: Radha
Age: 21

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 8


OBJECT ORIENETED PROGRAMMING WITH JAVA

Example Program to demonstrate Default, Parameterized & Copy Constructor


class Student
{
String name;
int age;

// Default Constructor
Student()
{
name = "Radha";
age = 18;
}

// Parameterized Constructor
Student(String n, int a)
{
name = n;
age = a;
}

// Copy Constructor
Student(Student s)
{
name = [Link];
age = [Link];
}

void display()
{
[Link]("Name: " + name);
[Link]("Age: " + age);
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 9
OBJECT ORIENETED PROGRAMMING WITH JAVA

[Link]();
}
}

public class Main


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

Student s1 = new Student(); // Default


Student s2 = new Student("Mohan", 20); // Parameterized
Student s3 = new Student(s2); // Copy

[Link]();
[Link]();
[Link]();
}
}

OUTPUT:
Name: Radha
Age: 18

Name: Mohan
Age: 20

Name: Mohan
Age: 20

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 10


OBJECT ORIENETED PROGRAMMING WITH JAVA

Constructor overloading
Constructor overloading means having multiple constructors in the same class with different parameter lists
(different number or type of arguments).
This allows objects to be created in multiple ways, providing flexibility for initialization depending on the
information available at the time of object creation.
Example:
class Student
{
String name;
int age;

// Default constructor (no parameters)


Student()
{
name = "Unknown";
age = 0;
}

// Constructor with one parameter


Student(String n)
{
name = n;
age = 0;
}
// Constructor with two parameters
Student(String n, int a)
{
name = n;
age = a;
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 11


OBJECT ORIENETED PROGRAMMING WITH JAVA

void display()
{
[Link]("Name: " + name + ", Age: " + age);
}
}
public class ConstructorOverloading
{
public static void main(String[] args)
{
Student s1 = new Student(); // Uses default constructor
Student s2 = new Student("Amith"); // Uses constructor with 1 parameter
Student s3 = new Student("Bharath", 20); // Uses constructor with 2
parameters

[Link](); // Output: Name: Unknown, Age: 0


[Link](); // Output: Name: Alice, Age: 0
[Link](); // Output: Name: Bob, Age: 20
}
}

OUTPUT:
Name: Unknown, Age: 0
Name: Amith, Age: 0
Name: Bharath, Age: 20

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 12


OBJECT ORIENETED PROGRAMMING WITH JAVA

Method Overloading:
Method overloading in Java means defining multiple methods with the same name in a class, but with
different parameter lists (different number, type, or order of parameters).

This allows methods to perform similar tasks but with different types or numbers of inputs, improving
code readability and usability

EXAMPLE:
class Calculator
{
// Method with 2 int parameters
int add(int a, int b)
{
return a + b;
}

// Method with 3 int parameters


int add(int a, int b, int c)
{
return a + b + c;
}

// Method with 2 double parameters


double add(double a, double b)
{
return a + b;
}
}

public class MethodOverloading


{

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 13


OBJECT ORIENETED PROGRAMMING WITH JAVA

public static void main(String[] args)


{

Calculator c = new Calculator();


[Link]("Sum of 2 integers: " + [Link](10, 20));
[Link]("Sum of 3 integers: " + [Link](10, 20, 30));
[Link]("Sum of 2 doubles: " + [Link](5.5, 4.5));
}
}
OUTPUT:
Sum of 2 integers: 30
Sum of 3 integers: 60
Sum of 2 doubles: 10.0

Static Members in Java


Static members in Java are variables and methods that belong to the class itself, rather than to any specific
instance of the class. They are declared using the static keyword.
Key Characteristics
• Shared Across All Instances: Static members are common to all objects of a class. There is only
one copy of each static member, regardless of how many objects are created.
• Accessed Using Class Name: They can be accessed directly using the class name, without creating
an object.

• Memory Management: Static members are stored in a special area of memory allocated to the
class, not to individual objects.
• Cannot Access Instance Data Directly: Static methods cannot directly access instance variables
or methods, as they do not belong to any specific object

Static Variable: A static variable is a variable that belongs to the class and is shared by all objects.
Static Method: A static method belongs to the class and can be called without creating an object.

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 14


OBJECT ORIENETED PROGRAMMING WITH JAVA

Below is a simple example demonstrating static variables and static methods:

class Employee
{
static String company = "TCS"; // Static variable
static void showCompany() // Static method
{
[Link]("Company: " + company);
}
}

public class CompanyDemo


{
public static void main(String[] args)
{
[Link](); // Call static method

[Link] = "Infosys"; // Change static variable

[Link](); // Call again


}
}
OUTPUT:
Company: TCS

Company: Infosys

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 15


OBJECT ORIENETED PROGRAMMING WITH JAVA

Recursion:
Recursion is a programming technique where a method calls itself to solve a problem by breaking it
down into smaller, more manageable subproblems. This approach continues until it reaches a
condition known as the base case or halting condition, which stops the recursion

How Recursion Works


• Recursive Call: The method invokes itself with modified parameters, aiming to bring the problem
closer to the base case each time.
• Base Case: This is the simplest scenario for the problem, where the recursion ends. Without a base
case, recursion would continue indefinitely, leading to a stack overflow error.
Java program to find the factorial of a given number using recursion
import [Link];
public class Factorial
{
// Recursive method
static int factorial(int n)
{
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
int result = factorial(num);
[Link]("Factorial of " + num + " is: " + result);
}
}
OUTPUT: Enter a number: 5
Factorial of 5 is: 120

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 16


OBJECT ORIENETED PROGRAMMING WITH JAVA

Access Control in Java


Access control in Java is managed through access modifiers that define the visibility and accessibility of
classes, methods, variables, and constructors. These modifiers help enforce encapsulation by restricting
access to the components of a class, thus enhancing security and modularity.
The Four Access Modifiers in Java
Modifier Class Package Subclass (same Subclass (different World (any
package) package) other class)
public Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes No
default (no modifier) Yes Yes Yes No No

private Yes No No No No

1. Public
Members declared public are accessible from anywhere in the program, regardless of package
boundaries. This is the least restrictive access level.
Example:
public class Student
{
public String name; // Public variable
public void display() // Public method
{
[Link]("Student Name: " + name);
}
public static void main(String[] args)
{
Student s1 = new Student();
[Link] = "Rahul"; // Accessing public variable
[Link](); // Calling public method
}
}
OUTPUT: Student Name: Rahul
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 17
OBJECT ORIENETED PROGRAMMING WITH JAVA

2. private
Members declared private are accessible only within the class they are declared. This is the most
restrictive access level and is used to hide sensitive data or implementation details.
Example:
class Student
{
private String name; // Private variable

// Public method to set private variable


public void setName(String n)
{
name = n;
}

// Public method to access private variable


public void display()
{
[Link]("Student Name: " + name);
}

public static void main(String[] args)


{
Student s1 = new Student();
// [Link] = "Rahul"; // Cannot access private variable directly
[Link]("Rahul"); // Use public method to set name
[Link](); // Output: Student Name: Rahul
}
}
OUTPUT:
Student Name: Rahul

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 18


OBJECT ORIENETED PROGRAMMING WITH JAVA

3. protected
Members declared protected are accessible within the same package and also in subclasses even if
they are in different packages. It provides a middle ground between public and default access.
Example:
class Student
{
protected String name; // Protected variable

protected void display() { // Protected method


[Link]("Student Name: " + name);
}
}

public class ProtectedDemo


{
public static void main(String[] args)
{
Student s1 = new Student();
[Link] = "Rahul"; // Accessing protected variable within same package
[Link](); // Accessing protected method

}
}
OUTPUT:
Student Name: Rahul

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 19


OBJECT ORIENETED PROGRAMMING WITH JAVA

4. default (package-private)
➢ When no access modifier is specified, the member is default (also called package-private).

➢ Accessible only within the same package

➢ Not accessible from classes in other packages

➢ More restrictive than protected but less restrictive than private.

Example:
class Student
{
String name; // Default access (no modifier)

void display() // Default method


{
[Link]("Student Name: " + name);
}
}

public class DefaultDemo


{
public static void main(String[] args)
{
Student s1 = new Student();
[Link] = "Rahul"; // Accessible because same package
[Link](); // Accessible because same package
}
}
OUTPUT:
Student Name: Rahul

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 20


OBJECT ORIENETED PROGRAMMING WITH JAVA

this keyword

This keyword refers to the current object in a method or constructor. The most common use of the this
keyword is to eliminate the confusion between class attributes and parameters with the same name
(because a class attribute is shadowed by a method or constructor parameter).

This can also be used to:

• Invoke current class constructor


• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

Example:
class Student
{
String name;
int age;
// Constructor
Student(String name, int age)
{
[Link] = name; // '[Link]' refers to instance variable
[Link] = age; // '[Link]' refers to instance variable
}
void display()
{
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
public static void main(String[] args)
{
Student s1 = new Student("Rahul", 20);
[Link](); // Output: Name: Rahul, Age: 20
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 21


OBJECT ORIENETED PROGRAMMING WITH JAVA

finalize() Method in Java

Definition:
The finalize() method is called by the garbage collector before an object is destroyed.
• It allows an object to perform cleanup operations (like closing files or releasing resources) before
memory is reclaimed.
• It is defined in the Object class.
Note: In modern Java versions, finalize() is deprecated because it is unpredictable
Key Points
1. Called automatically by garbage collector.
2. Used for cleanup operations before object is destroyed.
3. Should not be relied upon for critical cleanup because timing is uncertain.
4. Can be overridden in your class.

Garbage Collection in Java


Garbage Collection (GC) in Java is the process of automatically freeing memory by destroying objects that
are no longer referenced in the program.
• Helps in memory management.
• Performed automatically by the JVM, so you don’t need to explicitly free memory (unlike C/C++).
• Automatic memory management – JVM handles it.
• Reclaims memory of objects that are no longer in use.
• Uses the finalize() method before destroying an object (deprecated in newer versions, but still
sometimes used for demonstration).
• Triggered by calling [Link](), but JVM decides when exactly to run it.

Example:
class Student
{
String name;
Student(String name)
{
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 22
OBJECT ORIENETED PROGRAMMING WITH JAVA

[Link] = name;
}
// finalize() is called before object is garbage collected
protected void finalize() {
[Link]([Link] + " is garbage collected.");
}
}
public class GarbageDemo
{
public static void main(String[] args)
{
Student s1 = new Student("Rahul");
Student s2 = new Student("Anita");

s1 = null; // Remove reference to s1


s2 = null; // Remove reference to s2

[Link](); // Suggest JVM to perform garbage collection


[Link]("End of main method.");
}
}

OUTPUT:
End of main method.
Rahul is garbage collected.
Anita is garbage collected.

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 23


OBJECT ORIENETED PROGRAMMING WITH JAVA

INHERITANCE
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of
another. With the use of inheritance, the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class).
(OR)
The mechanism of deriving a new class from an old one is called inheritance. The old class is known as
the base class or super class or parent class and the new one is called the subclass or derived class or child
class.
Inheritance is implemented using the extends keyword.
Inheritance may take different forms:
1. Single inheritance (only one super class)
2. Multiple inheritances (several super classes)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multilevel inheritance (Derived from a derived class)
Why Use Inheritance?
• Code Reusability: Common code can be written once in a superclass and reused in multiple
subclasses.
• Extensibility: Subclasses can extend or enhance the functionality of a superclass.
• Polymorphism: Enables method overriding, allowing subclasses to provide
specific implementations for methods defined in the superclass.
• Hierarchical Organization: Helps manage and organize code in a logical, hierarchical manner
Basic Syntax:
class Superclass
{
// fields and methods
}
class Subclass extends Superclass
{
// additional fields and methods
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 24
OBJECT ORIENETED PROGRAMMING WITH JAVA

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.
Example:
class Animal
{
void eat()
{
[Link]("This animal eats food");
}
}

class Dog extends Animal


{
void bark() {
[Link]("Dog barks");
}
}
public class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
[Link](); // Inherited from Animal
[Link]();
}
}
OUTPUT:
This animal eats food
Dog barks

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 25


OBJECT ORIENETED PROGRAMMING WITH JAVA

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. Or A class inherits from a class, which inherits from
another class (a chain).
Example:
class Animal
{
void eat()
{
[Link]("Eats food");
}
}
class Dog extends Animal
{
void bark() {
[Link]("Barks");
}
}

class Puppy extends Dog


{
void weep()
{
[Link]("Weeps");
}
}
public class Test
{
public static void main(String[] args)
{
Puppy p = new Puppy();
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 26
OBJECT ORIENETED PROGRAMMING WITH JAVA

[Link]();
[Link]();
[Link]();
}
}
OUTPUT:
Eats food
Barks
Weeps
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.
Example:
class Animal
{
void eat()
{
[Link]("Eats food");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Barks");
}
}
class Cat extends Animal
{
void meow()
{
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 27
OBJECT ORIENETED PROGRAMMING WITH JAVA

[Link]("Meows");
}
}
public class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
[Link]();
[Link]();

Cat c = new Cat();


[Link]();
[Link]();
}
}
OUTPUT:
Eats food
Barks
Eats food
Meows
4. Multiple Inheritance via Interfaces
Java supports multiple inheritance through interfaces.
In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes. Please note that Java does not support multiple inheritances with classes. In Java, we
can achieve multiple inheritances only through Interfaces
Example:
// Interface for Dog
interface Dog
{
void bark();
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 28
OBJECT ORIENETED PROGRAMMING WITH JAVA

}
// Interface for Cat
interface Cat
{
void meow();
}
// Class implementing both interfaces
class Pet implements Dog, Cat
{
public void bark()
{
[Link]("Dog barks: Woof Woof");
}

public void meow()


{
[Link]("Cat meows: Meow Meow");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Pet myPet = new Pet();
[Link](); // Dog activity
[Link](); // Cat activity
}
}
OUTPUT:
Dog barks: Woof Woof

Cat meows: Meow Meow

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 29


OBJECT ORIENETED PROGRAMMING WITH JAVA

OVERRIDING METHODS:
Method overriding occurs when a subclass provides its own implementation of a method that is already
defined in its superclass.
• Same method name
• Same parameters (signature)
• Same return type (or compatible type)
It is used to change or extend the behavior of an inherited method.

Usage of Java Method Overriding


• Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
• Method overriding is used for runtime polymorphism
Illustration of method overriding
// Superclass
class Animal
{
void sound()
{
[Link]("Animal makes a sound");
}
}

// Subclass
class Cat extends Animal
{
@Override
void sound()
{
[Link]("Cat says: Meow Meow");
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 30


OBJECT ORIENETED PROGRAMMING WITH JAVA

public class OverridingDemo


{
public static void main(String[] args)
{
Animal a = new Animal();
[Link](); // Calls superclass method

Cat c = new Cat();


[Link](); // Calls subclass overridden method
}
}
OUTPUT:
Animal makes a sound
Cat says: Meow Meow

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 31


OBJECT ORIENETED PROGRAMMING WITH JAVA

Dynamic Dispatch or Runtime Polymorphism:


Dynamic Dispatch is a process in which a call to an overridden method is resolved at runtime rather than
compile-time.
Dynamic Dispatch is the process by which a call to an overridden method is resolved at runtime rather than
compile time.
• It happens when a superclass reference points to a subclass object.
• Ensures that the subclass version of the method is called.
• This is a key concept in runtime polymorphism.
Example:
// Superclass
class Animal
{
void sound()
{
[Link]("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal
{
@Override
void sound()
{
[Link]("Dog barks: Woof Woof");
}
}
public class DynamicDispatchDemo
{
public static void main(String[] args)
{
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 32
OBJECT ORIENETED PROGRAMMING WITH JAVA

Animal a; // Superclass reference


a = new Animal(); // Refers to Animal object
[Link](); // Calls Animal's method

a = new Dog(); // Refers to Dog object


[Link](); // Calls Dog's overridden method
}
}
OUTPUT:
Animal makes a sound
Dog barks: Woof Woof

ABSTRCAT METHODS & CLASSES:


Definition:
• Abstract Class: A class declared with the abstract keyword.
o It cannot be instantiated directly.
o It can contain abstract methods (without body) and concrete methods (with body).
• Abstract Method: A method declared with abstract keyword without a body.
o Must be overridden in a subclass.
o Example: abstract void sound();
Abstract classes are used to provide a base class with some common implementation while forcing
subclasses to implement specific methods.

Example:
// Abstract class
abstract class Animal
{
abstract void sound(); // Abstract method
void sleep() // Concrete method
{
[Link]("Animal is sleeping");
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 33


OBJECT ORIENETED PROGRAMMING WITH JAVA

// Subclass
class Dog extends Animal
{
@Override
void sound()
{
[Link]("Dog barks: Woof Woof");
}
}

public class AbstractDemo


{
public static void main(String[] args)
{
// Animal a = new Animal(); // Cannot create object of abstract class
Dog d = new Dog(); // Subclass object
[Link](); // Calls overridden method
[Link](); // Calls concrete method from abstract class
}
}
OUTPUT:
Dog barks: Woof Woof
Animal is sleeping

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 34


OBJECT ORIENETED PROGRAMMING WITH JAVA

Final Variables:
• A final variable is a constant, and its value cannot be modified after initialization.
• You must initialize a final variable when it's declared or in the constructor.
• If a final variable holds a reference to an object, the object's properties can still be modified,
but the variable itself will always refer to the same object.

Example:

class FinalVariableDemo

public static void main(String[] args)

final int MAX_AGE = 100; // final variable

[Link]("Max age: " + MAX_AGE);

// MAX_AGE = 120; // Error: cannot change final variable

}
Final Methods:
• A final method cannot be overridden by subclasses.
• This ensures that the method's implementation remains consistent across all subclasses.
• Methods that should not be overridden, especially those in the constructor or related to
theobject's core state, are often made final.

Example:
class Animal
{
final void eat()
{
[Link]("Animal is eating");
}
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 35
OBJECT ORIENETED PROGRAMMING WITH JAVA

class Dog extends Animal


{
// void eat() { } // Error: cannot override final method
}
public class FinalMethodDemo
{
public static void main(String[] args)
{
Dog d = new Dog();
[Link]();
}
}
Final Classes:
• A final class cannot be extended or subclassed.
• This prevents inheritance and is useful for creating immutable classes like the String class.
• Final classes cannot have any subclasses.

Example:
final class Calculator
{
int add(int a, int b)
{
return a + b;
}
}

// class AdvancedCalculator extends Calculator { } // Error: cannot inherit final class

public class FinalClassDemo


{
public static void main(String[] args)
{
Calculator c = new Calculator();
[Link]("Sum: " + [Link](5, 3));
}
}
OUTPUT: Sum: 8

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 36


OBJECT ORIENETED PROGRAMMING WITH JAVA

ARRAYS
Java array is a collection of homogeneous data elements. It is an object which contains elements of a
similar data type. Additionally, the elements of an array are stored in a contiguous memory location. It is
a data structure where we store similar elements. Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Advantages:
• Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
• Random access: We can get any data located at an index position. Arrays are used to store multiple
values in a single variable, instead of declaring separate variables for each value.

There are two types of arrays:


1. One-dimensional array
2. Multi-dimensional array

One-dimensional array:
A one-dimensional array can be visualized as a single row or a column of array elements that are
represented by a variable name and whose elements are accessed by index values.
one-dimensional array in java must deal with only one parameter. Entities of similar types can be stored
together using one-dimensional arrays. It can store primitive data types (int, float, char, etc.) or objects.
Declaration of one-dimensional array
data-type var-name[];
OR
data-type[] var-name;
OR
data-type []var-name;

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 37


OBJECT ORIENETED PROGRAMMING WITH JAVA

An array declaration has two components:


data-type: The data type determines the data type of each element present in the array-like char, int, float,
objects etc.
var-name: It is the name of the reference variable which points to the array object stored in the heap
memory.
[ ] : It is called subscript.
Construction of one-dimensional array in Java
There are mainly two ways to create an array in java :
1. We can declare and store the values directly at the time of declaration:
int marks[ ] = { 90, 97, 95, 99, 100 };
2. The second way of creating an array is by first declaring the array and then allocating the memory
through the new keyword :
var-name = new type[size];
eg: int[] Number = new int[10];
Example
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
public class Main
{
public static void main(String args[])
{
//declaration and instantiation of an array
int a[]=new int[5];
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)
{
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 38
OBJECT ORIENETED PROGRAMMING WITH JAVA

[Link](a[i]);
}
}
}
Output:
10
20
70
40
50
Two-Dimensional Array
A 2D array is like a table made of rows and columns. It is a data structure used to store data in a grid-like
format with rows and columns.
You can think of it as a table or matrix, where:
• Each element is accessed using two indices – one for the row and one for the column.
• It is declared as: dataType[][] arrayName;
// Declaring 2D array
DataType[][] ArrayName;
// Creating a 2D array
ArrayName = new DataType[r][c];
Eg : //Declaring 2D array
int[][] a;
//Creating a 2D array
a = new int[3][3];

// Creating a 2D Array
DataType[][] ArrayName = new DataType[r][c]
// Accessing an element
DataType var = ArrayName[i][j];

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 39


OBJECT ORIENETED PROGRAMMING WITH JAVA

Example for Two Dimensional array


public class Main
{
public static void main(String args[])
{
int arr[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
Output
123
456
789

Variable-size array:
. The most common alternative is ArrayList, you should use the ArrayList class from the [Link]
package.

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 40


OBJECT ORIENETED PROGRAMMING WITH JAVA

Definition:

In Java, arrays have a fixed size once they are created —you can't change the size of an array after
initialization. However, you can simulate variable-sized arrays using other data structures

A variable-size array (also called dynamic array) is an array-like structure whose size can change during
runtime.

• In Java, normal arrays have fixed size, so we use ArrayList for variable-size arrays.

• ArrayList is part of [Link] package and can grow or shrink dynamically.

Example:

import [Link];

public class SimpleArray

public static void main(String[] args)

ArrayList<String> students = new ArrayList<>(); // create variable-size array

[Link]("Rahul"); // add element

[Link]("Anita"); // add another element

[Link](students); // print all elements

OUTPUT:

[Rahul, Anita]

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 41


OBJECT ORIENETED PROGRAMMING WITH JAVA

STRINGS
String is a sequence of characters. In Java, string is an object that represents a sequence of characters. The
[Link] class is used to create a string object.
There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
By new keyword
String s=new String("Welcome");
//creates two objects and one reference variable
Example
public class StringExample
{
public static void main(String[] args)
{
// Creating a string
String name = "John";
// Printing the string
[Link]("Hello, " + name + "!");
// String length
[Link]("Length of name: " + [Link]());
}
}
Output
Hello, John!
Length of name: 4

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 42


OBJECT ORIENETED PROGRAMMING WITH JAVA

String handling functions in Java


String handling functions in Java are built-in methods provided by the String class that allow you to
perform various operations on strings, such as comparing, searching, modifying, and extracting parts of a
string.
The string class has a set of built-in-methods, defined below.
Function Description Example
toUpperCase() Converts string to uppercase "hello".toUpperCase() → "HELLO"
toLowerCase() Converts string to lowercase "JAVA".toLowerCase() → "java"
charAt(index) Returns the character at the given index "Java".charAt(1) → 'a'
substring(start, end) Extracts part of the string "Hello".substring(1, 4) → "ell"
equals(str) Checks if two strings are equal "hi".equals("hi") → true
contains(str) Checks if string contains another string "hello".contains("lo”) → true
replace(a, b) Replaces characters "apple".replace('a', 'A') → "Apple"
length() Returns the length of the string "Hello".length() →5

Example program
public class StringHandlingExample
{
public static void main(String[] args)
{
String text = "Hello Java";
// 1. length()
[Link]("Length: " + [Link]());

// 2. toUpperCase()
[Link]("Uppercase: " + [Link]());

// 3. toLowerCase()
[Link]("Lowercase: " + [Link]());

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 43


OBJECT ORIENETED PROGRAMMING WITH JAVA

// 4. charAt()
[Link]("Character at index 1: " + [Link](1));

// 5. substring()
[Link]("Substring (0 to 5): " + [Link](0, 5));

// 6. equals()
[Link]("Equals 'Hello Java': " + [Link]("Hello Java"));

// 7. contains()
[Link]("Contains 'Java': " + [Link]("Java"));

// 8. replace()
[Link]("Replace 'Java' with 'World': " + [Link]("Java", "World"));
}
}
Output
Length: 10
Uppercase: HELLO JAVA
Lowercase: hello java
Character at index 1: e
Substring (0 to 5): Hello
Equals 'Hello Java': true
Contains 'Java': true
Replace 'Java' with 'World': Hello World

StringBuffer Classes
StringBuffer in Java is a special class used to create and manage strings that can be changed or modified
after they are created. In contrast, regular String objects in Java cannot be changed once they are created
(they are immutable).

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 44


OBJECT ORIENETED PROGRAMMING WITH JAVA

Key Features of StringBuffer


• Mutable: You can change the content of a StringBuffer object without creating a new object every
time.
• Efficient for Modifications: It is more memory and performance efficient when you need to modify
text frequently, such as adding, removing, or changing characters.
• Thread-Safe: StringBuffer is designed to be safe to use when multiple threads might be changing the
same string at the same time
Common StringBuffer Methods (with Simple Examples)

Method What it does Example and Output

append() Adds text to the end [Link](" World"); // "Hello World"

insert() Inserts text at a given position [Link](5, ","); // "Hello, World"

delete() Removes text between positions [Link](5, 7); // "HelloWorld"

replace() Replaces text between positions [Link](1, 3, "Java"); // "HJavalo"

reverse() Reverses the entire string [Link](); // "dlroWolleH"

public class Sample


{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // "Hello World"
[Link](5, ","); // "Hello, World"
[Link](5, 7); // "HelloWorld"
[Link](1, 3, "Java"); // "HJavalo"
[Link](); // "olavaJH"
[Link](sb);
}
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 45
OBJECT ORIENETED PROGRAMMING WITH JAVA

Wrapper classes in java


The wrapper class in java provides the mechanism to convert primitive datatypes in to objects of
corresponding wrapper class and object of wrapper class to corresponding primitive types.
Each primitive type has a corresponding wrapper class in [Link] package.
List of Wrapper Classes
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

To implement wrapper classes two mechanisms are used:


1. Autoboxing
2. Unboxing
Auto boxing:
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing. For example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.
Wrapper Class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class Wrapper Example1
{
public static void main(String args[])
{
//Converting int into Integer

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 46


OBJECT ORIENETED PROGRAMMING WITH JAVA

int a=20;
Integer b=[Link](a) ;//converting int into Integer explicitly
Integer c=a; //autoboxing, now compiler will write [Link](a) internally
[Link](a+" "+b+" "+c);
}
}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known asunboxing. It
is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper
classes to convert the wrapper type into primitives.
Wrapper Class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int b=[Link] Value();//converting Integer to int explicitly
int c=a;//unboxing, now compiler will write [Link]() internally
[Link](a+" "+b+" "+c);
}
}
Output:
333

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 47


OBJECT ORIENETED PROGRAMMING WITH JAVA

INTERFACES IN JAVA
Interfaces: Multiple Inheritance
• An interface is a blueprint for classes.
• It can contain:
o Abstract methods (methods without body)
o Constants (variables are public static final by default)
• A class implements an interface and provides concrete implementations for all its methods.
• Supports multiple inheritance in Java (a class can implement multiple interfaces).

DEFINING INTERFACES:
An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a
major difference. The difference is that interfaces define only abstract methods and final fields.

This means that interfaces do not specify any code to implement these methods and data fields contain only
constants. The syntax for defining an interface is very similar to that for defining a class.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Here, interface is the keyword and interfacename is any valid Java variable(just like class names).

Note that all variables are declared as constants.

EXTENDING INTERFACES
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other
interfaces. The new subinterface will inherit all the members of the super interface in the manner similar
to subclasses. This is achieved using the keyword extends.

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 48


OBJECT ORIENETED PROGRAMMING WITH JAVA

SYNTAX:
interface name2 extends name1
{
Body of name2
}
For example, we can put all the constants in one interface and the methods in the other. This will enable
us to use the constants in classes where the methods are not required. Example
interface ItemConstants
{
int code=1001 ;
String name=“Fan”;
}
interface Item extends ItemConstants
{
Void display();
}
Implementing Interface In Java
To implement an interface in Java, a class uses the implements keyword in its declaration, followed by a
comma-separated list of the interfaces it implements.

This establishes a contract where the class must provide implementations for all the methods defined in
the interface.
class classname implements interfacename
{
body of classname.
}

Here the class classname "implements" the interface interfacename. A more general form of
implementation may look like this:

class classname extends superclass implements interface1, interface2,…….

{
body of classname

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 49


OBJECT ORIENETED PROGRAMMING WITH JAVA

}
This shows that a class can extend another class while implementing interfaces.

Program: Implementing interfaces


interface Area
// Interface
interface Animal
{
void sound(); // Abstract method
void sleep(); // Abstract method
}

// Class implementing the interface


class Dog implements Animal
{
// Provide implementation for sound()
public void sound() {
[Link]("Dog barks: Woof Woof");
}

// Provide implementation for sleep()


public void sleep()
{
[Link]("Dog is sleeping");
}
}

public class InterfaceImplementationDemo


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

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 50


OBJECT ORIENETED PROGRAMMING WITH JAVA

Dog d = new Dog(); // Create object of implementing class


[Link](); // Call implemented method
[Link](); // Call implemented method
}
}
OUTPUT:

Dog barks: Woof Woof


Dog is sleeping

Implementing Multiple Inheritance via Interfaces


Java supports multiple inheritance through interfaces.
In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes. Please note that Java does not support multiple inheritances with classes. In Java, we
can achieve multiple inheritances only through Interfaces
Example:
// Interface for Dog
interface Dog
{
void bark();
}
// Interface for Cat
interface Cat
{
void meow();
}
// Class implementing both interfaces
class Pet implements Dog, Cat
{
public void bark()
{
[Link]("Dog barks: Woof Woof");
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 51
OBJECT ORIENETED PROGRAMMING WITH JAVA

public void meow()


{
[Link]("Cat meows: Meow Meow");
}
}
public class AnimalDemo
{
public static void main(String[] args)
{
Pet myPet = new Pet();
[Link](); // Dog activity
[Link](); // Cat activity
}
}
OUTPUT:
Dog barks: Woof Woof
Cat meows: Meow Meow

Java Nested Interface:


An interface, i.e., declared within another interface or class, is known as a nested interface. The nested
interfaces are used to group related interfaces so that they can be easy to maintain. The nested interface
must be referred to by the outer interface or class. It can't be accessed directly.
Syntax of nested interface which is declared within the interface
interface interface_name
{
...
interface nested_interface_name
{
...
}
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 52
OBJECT ORIENETED PROGRAMMING WITH JAVA

}
Syntax of nested interface which is declared within the class
class class_name
{
...
interface nested_interface_name
{
...
}
} // Outer interface
Example:
interface Vehicle
{
// Nested interface
interface Engine
{
void start();
}
}
// Class implementing the nested interface
class Car implements Vehicle. Engine
{
public void start()
{
[Link]("Engine started");
}
public static void main(String[] args)
{
Car myCar = new Car();
[Link](); // Output: Engine started
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 53


OBJECT ORIENETED PROGRAMMING WITH JAVA

}
How it works:
• Engine is a nested interface inside Vehicle.
• Car implements the nested interface using implements [Link].
• In main, we create a Car object and call start ()

Various Forms of Interface Implementation in Java


Java interfaces can be implemented in several ways, each serving different purposes and offering
flexibility in design. Here are the main forms, explained with concise examples:
1. Regular Interface Implementation:
• A class can implement an interface using the implements keyword, stating that it will
provide implementations for the interface's methods.
For example:
interface MyInterface
{
void myMethod();
}
class MyClass implements MyInterface
{
public void myMethod()
{
// Implementation for myMethod
}
}
2. Multiple Interface Implementation:
• A class can implement multiple interfaces, inheriting the method signatures (contracts) of
all interfaces.
• This enables a class to have multiple behaviors.
For example:
interface Interface1
{

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 54


OBJECT ORIENETED PROGRAMMING WITH JAVA

void method1();
}
interface Interface2
{
void method2();
}
class MyClass implements Interface1, Interface2
{
public void method1()
{
// Implementation for method1
}
public void method2()
{
// Implementation for method2
}
}
3. Interface Extension:
• Interfaces can extend other interfaces using the extends keyword, creating a hierarchy of
interfaces.
• This allows for defining more specific behaviors or grouping related methods into a
hierarchy.
For example:
interface BaseInterface
{
void base Method();
}
interface ExtendedInterface extends BaseInterface
{
void extended Method();
}

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 55


OBJECT ORIENETED PROGRAMMING WITH JAVA

4. Interface with Abstract Methods:


• Interfaces can contain abstract methods (methods without implementation) that must be
implemented by the class that implements the interface.
• This defines the contract of the interface

Accessing Interface Variables


Key Rules for Interface Variables:
1. Always public, static, and final – even if you don’t specify them.
2. Belong to the interface, not to objects.
3. Can be accessed using:
✓ The interface name
✓ Or by any class that implements the interface
Syntax:
interface MyInterface
{
int VALUE = 10; // This is implicitly public, static, and final
}
This is equivalent to:
interface MyInterface
{
public static final int VALUE = 10;
}
Example:
interface MyInterface
{
int VALUE = 100; // implicitly public static final
}

class Demo implements MyInterface


{
public void show()
MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 56
OBJECT ORIENETED PROGRAMMING WITH JAVA

{
// Access via interface name (recommended)
[Link]("Value is: " + [Link]);

// Access via implementing class (also valid)

[Link]("Value via class: " + VALUE);


}
public static void main(String[] args) {
Demo obj = new Demo();
[Link]();
}
}
OUTPUT:
Value is: 100
Value via class: 100

MALLESH MB, ASSISTANT PROFESSOR, DEPT., OF BCA, NCM, KOLLEGAL 57

You might also like