Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views27 pages

Unit 2 Classess and Objects - Updated

The document outlines key concepts of Java programming, focusing on classes, objects, inheritance, and encapsulation. It details the structure of classes, access modifiers, constructors, and method overloading/overriding, providing examples for clarity. Additionally, it discusses inheritance types and the significance of encapsulation in data management within Java applications.

Uploaded by

mo.learning.55
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)
6 views27 pages

Unit 2 Classess and Objects - Updated

The document outlines key concepts of Java programming, focusing on classes, objects, inheritance, and encapsulation. It details the structure of classes, access modifiers, constructors, and method overloading/overriding, providing examples for clarity. Additionally, it discusses inheritance types and the significance of encapsulation in data management within Java applications.

Uploaded by

mo.learning.55
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/ 27

403: JAVA Programming Language | SYBCA-(SEM-4)

Unit 2: Classes and Objects

2.1 Simple Class, Field


2.2 Access Controls, Object creation
2.3 Construction and initialization
2.4 Inheritance and Polymorphism in Java
2.4.1 Data encapsulation, overriding and overloading methods
2.5 this and super keywords
2.6 Static members, static block, static class
2.7 Interfaces:
2.7.1 Introduction to Interfaces, Interface Declaration.
2.7.2 Inheriting and Hiding concepts.
2.7.3 Inheriting, Overloading and overriding Methods and constructors.
2.7.4 Interfaces Implementation.

2.1 Simple Class and Fields

Definition of a Class

 A class is a template that specifies the attributes and behavior of things or objects.
 A class is a blueprint or prototype from which objects are created.
 A class is the implementation of an abstract data type (ADT).
 Class is a combination of Data Members and Member Functions.

Syntax of a Class

classClassName {
Datatype variable1;
Datatype variable2; DataMembers
Datatype variableN;

return_type methodname1 (parameter-list) {


// body of method
}
return_typemethodname2(parameter-list) {
// body of method MemberFunctions
}
………………
return_typemethodnameN(parameter-list) {
// body of method
}
}

Sutex Bank College of Computer Applications & Science, Amroli |1


403: JAVA Programming Language | SYBCA-(SEM-4)

Key Characteristics

 A class is declared using the class keyword.


 The data, or variables, defined within a class are called instance variables. Each instance
of the class (object) contains its own copy of these variables. The data of one object is
separate and unique from another object.
 The methods and variables defined within a class are referred to as members of the
class.
 Methods contain the actual code for operations.

Method Syntax

return_typemethod_name(parameter-list) {
// body of method
}

 return_type: Specifies the type of data the method returns. If no value is returned, the
type must be void.
 method_name: Specifies the name of the method. It must be a unique identifier within
the current scope.
 parameter-list: A sequence of type and identifier pairs separated by commas. If no
parameters exist, the list is empty.

Return Value

 Methods with a return type other than void use the return statement to pass values
back to the calling method.

Syntax:

return value;

 Here, value is the data returned to the calling method.

Example: Simple Class

classResult {
doublemarks1 = 89;
doublemarks2 = 95;
doublemarks3 = 92;

Sutex Bank College of Computer Applications & Science, Amroli |2


403: JAVA Programming Language | SYBCA-(SEM-4)

doublepercentage() {
return(marks1 +marks2+marks3)/3;
}
}

Method Call Syntax

var_name = object_name.method_name(parameter-list);

Example:

Result r1 = new Result(); // Create an object


double per = r1.percentage(); // Call the method

 In the above example, r1 is an object. The method percentage() is called and assigned to
the variable per.

2.2 Visibility Controls in Java

Java provides several access modifiers to define visibility and access levels for classes, variables,
methods, and constructors. The four access levels are:

1. Package/Friendly (Default)
o Visible to all classes within the same package.
o No explicit modifier is needed.
2. Private
o Visible only within the class where it is declared.
3. Public
o Visible within the class and to all other classes, regardless of package.
4. Protected
o Visible within the same package and accessible by subclasses.

Default Access Modifier (No Keyword)

 This modifier is applied when no access control keyword is specified.


 Members are accessible to all classes within the same package.
 Note: Default access cannot be applied to interface methods since they are always
public.

Sutex Bank College of Computer Applications & Science, Amroli |3


403: JAVA Programming Language | SYBCA-(SEM-4)

Example:

Class A
{
String str = "Hi";

void a() {
System.out.println(str);
}
}

Private Access Modifier (private)

 Methods, variables, and constructors declared private are only accessible within the
same class.
 This is the most restrictive access level.
 Classes and interfaces cannot be declared private.
 To expose private variables outside the class, getter and setter methods must be used.

Example:

class A {
private String s1 = "Hello";

String getName() {
returns1;
}
}

 In the above example, s1 is private, meaning it cannot be accessed directly from other
classes. The getName() method provides controlled access to it.

Public Access Modifier (public)

 The public keyword allows unrestricted access to a class, method, constructor, or


variable.
 Members declared public are accessible from any class, even those in different
packages.
Example:
public class Demo {
public static void main(String[] args) {
System.out.println("This is a public method!");
}}

Sutex Bank College of Computer Applications & Science, Amroli |4


403: JAVA Programming Language | SYBCA-(SEM-4)

 The main() method must always be public so that the Java interpreter can call it to start
the program.

Protected Access Modifier (protected)


 Protected members can be accessed:
1. Within the same package.
2. By subclasses, even if they are in a different package.
 The protected modifier cannot be applied to classes or interfaces.

Example:

package p1;

class A {
float f1;
protectedint i1;
}

package p1;

class B {
public void getData() {
A a1 = new A(); // Instance of class A
a1.f1 = 19;
a1.i1 = 12; // Accessing protected variable
}
}

 In this example, i1 is a protected variable of class A. It is accessible in class B because


they belong to the same package.

2.3 Constructor

Definition

 A constructor is a special type of method used to initialize an object.


 It is invoked(call) automatically at the time of object creation.

Rules for Defining a Constructor

1. The constructor name must be the same as the class name.


2. A constructor must not have a return type, not even void.
3. The return type of a constructor is implicitly the class type itself.

Sutex Bank College of Computer Applications & Science, Amroli |5


403: JAVA Programming Language | SYBCA-(SEM-4)

Types of Constructors

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

1. Default Constructor

 A constructor without any parameters is called a default constructor.


 If no constructor is explicitly defined in the class, the compiler automatically provides a
default constructor.

Example:

class A {
A() { // Default constructor
System.out.println("Default constructor called..");
}

public static void main(String[] args) {


A a = new A();
}
}

Output:

Default constructor called..

2. Parameterized Constructor

 A constructor that accepts arguments is called a parameterized constructor.


 It allows assigning different values to distinct objects during creation.
 Note: If only parameterized constructors are defined, the default constructor will not be
automatically generated.
Example:
class A {
int a;
String s1;

A(int b, String s2) { // Parameterized constructor


a = b;
s1 = s2;
}

Sutex Bank College of Computer Applications & Science, Amroli |6


403: JAVA Programming Language | SYBCA-(SEM-4)

void display() {
System.out.println("Value of parameterized constructor is :: " + a + " and " + s1);
}

public static void main(String[] args) {


A obj = new A(10, "Hello");
obj.display();
}
}

Output:

Value of parameterized constructor is :: 10 and Hello

3. Copy Constructor

 A copy constructor is a constructor that takes one parameter of the same class type.
 It is used to create a new object as a copy of an existing object.
 The copy is independent of the original object, occupying a different memory address.

Example:

class Triangle {
doublebase, height;

// Copy constructor
Triangle(Triangle t1) {
base = t1.base;
height = t1.height;
}
}

4. Overloaded Constructors

 Constructor overloading allows defining multiple constructors within a class, each with a
different signature.
 Unlike methods, constructors do not have a return type.

Passing Object as a Parameter


 To construct a new object initially identical to an existing object, define a constructor
that takes an object of the same class as a parameter.

Sutex Bank College of Computer Applications & Science, Amroli |7


403: JAVA Programming Language | SYBCA-(SEM-4)

Example:

class Triangle {
double base, height;

Triangle() // Default constructor


{
base= height = 1;
System.out.println("I am Default Constructor");
}

Triangle(double b, double h) { // Parameterized constructor


base= b;
height = h;
}

Triangle(Triangle t1) // Copy constructor


{
base=t1.base;
height = t1.height;
}

double area() { // Calculate and return area of triangle


return (0.5*base*height);
}
}

classconstructor_ex {
public static void main(String[] args) {
Triangle t1 = new Triangle(); //Default constructor call
Triangle t2 = new Triangle(10, 20); // Parameterized constructor call
Triangle t3 = new Triangle(t2); // copy constructor call

System.out.println("Area of Triangle for t1 is " + t1.area());


System.out.println("Area of Triangle for t2 is " + t2.area());
System.out.println("Area of Triangle for t3 is " + t3.area());
}
}
Output:
I am Default Constructor
Area of Triangle for t1 is 0.5
Area of Triangle for t2 is 100.0
Area of Triangle for t3 is 100.0

Sutex Bank College of Computer Applications & Science, Amroli |8


403: JAVA Programming Language | SYBCA-(SEM-4)

2.4 Inheritance

Definition
 Inheritance is the process by which a class can acquire the properties and methods of its
parent class.
 A child class (derived class) is created from a parent class (base class).
 Inheritance enables:
o Reusability: Methods and fields from the parent class can be reused.
o Extensibility: New methods and fields can be added to the child class.
 All properties of a superclass, except private members, can be inherited in a subclass
using the extendskeyword.
 The inherited fields can be used directly, just like any other fields. You can declare a field
in the subclass with the same name as the one in the superclass.
 You can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 You can write a new instance method in the subclass that has the same signature as the
one in the superclass.(overriding it).

Types of Inheritance

Single Inheritance:
A class is derived from a single parent class.
Example:
class A {
public void displayA() {
System.out.println("Class A method");
}
}
class B extends A {
public void displayB() {
System.out.println("Class B method");
}
}
Multilevel Inheritance:
A class is derived from a class that is itself derived from
another class.
Example:
class A { ... }
class B extends A { ... }
class C extends B { ... }
Multiple Inheritance:
Not supported directly in Java through classes to avoid
ambiguity.

Sutex Bank College of Computer Applications & Science, Amroli |9


403: JAVA Programming Language | SYBCA-(SEM-4)

Hierarchical Inheritance:
Multiple classes are derived from a single parent class.
Example:
class A { ... }
class B extends A { ... }
class C extends A { ... }
Hybrid Inheritance:
Combination of single and multiple inheritance. Not
directly supported in Java.

Example

class A {
void displayA() {
System.out.println("Class A method");
}
}
class B extends A { // Single Inheritance
void displayB() {
System.out.println("Class B method");
}
}
class C extends B { // Multilevel Inheritance
void displayC() {
System.out.println("Class C method");
}
}
class D extends A { // Hierarchical Inheritance
void displayD() {
System.out.println("Class D method");
}
}
class Trial {
public static void main(String[] args) {
B b = new B();
C c = new C();
D d = new D();

b.displayB();
c.displayC();
d.displayD();
}}

Sutex Bank College of Computer Applications & Science, Amroli |10


403: JAVA Programming Language | SYBCA-(SEM-4)

2.4.1 Encapsulation

Definition

 Encapsulation is the mechanism of binding together data and the methods that
manipulate it, hiding implementation details from the outside world.
 It combines data hiding and abstraction.
 Achieved by:
o Declaring variables as private.
o Providing public getter and setter methods for controlled access.

Example:

class Person {
private String name;
privateint age;

String getName() { return name; }


void setName(String name) { this.name = name; }
int getAge() { return age; }
void setAge(int age) { this.age = age; }
}

class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("Vidhya");
person.setAge(30);

System.out.println("Name: " + person.getName());


System.out.println("Age: " + person.getAge());
}
}

Advantages:

 Data Hiding  Reusability


 Increased Flexibility  Easier Testing
2.4.2 Method Overriding

Definition

 Occurs when a subclass provides a specific implementation of a method that is already


defined in its superclass.
 Enables runtime polymorphism.

Sutex Bank College of Computer Applications & Science, Amroli |11


403: JAVA Programming Language | SYBCA-(SEM-4)

Example:

class A {
public void display() {
System.out.println("Class A");
}
}

class B extends A {
public void display() {
System.out.println("Class B");
}
}

class Trial {
public static void main(String[] args) {
A a = new A();
A b = new B();

a.display(); // Output: Class A


b.display(); // Output: Class B
}}
Dynamic Method Dispatch

Definition

 Also known as runtime polymorphism, it is the process of resolving method calls at


runtime based on the object being referenced.

Example:

class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
void callme() {
System.out.println("Inside B's callme method");
}
}

class DispatchDemo {
public static void main(String[] args) {
A obj; // Reference of type A

Sutex Bank College of Computer Applications & Science, Amroli |12


403: JAVA Programming Language | SYBCA-(SEM-4)

obj = new A();


obj.callme(); // Output: Inside A's callme method

obj = new B();


obj.callme(); // Output: Inside B's callme method
}
}

2.4.1 Method Overloading

Definition

 Method Overloading occurs when a class has multiple methods with the same name
but different parameters.
 It is also known as compile-time (static) polymorphism.

Characteristics
 The same method name can be used with:
1. Different numbers of parameters
2. Different data types of parameters
3. Different order of parameters
 Overloading methods with different return types is not allowed.
 During compilation, the compiler determines which method to call based on the type
and number of arguments passed.

Example:

class OverloadingDemo {
// Method with two integer parameters
void sum(int a, int b) {
System.out.println("Sum of (a+b) is:: " + (a + b));
}

// Method with three integer parameters


void sum(int a, int b, int c) {
System.out.println("Sum of (a+b+c) is:: " + (a + b + c));
}

// Method with two double parameters


void sum(double a, double b) {
System.out.println("Sum of double (a+b) is:: " + (a + b));
}

Sutex Bank College of Computer Applications & Science, Amroli |13


403: JAVA Programming Language | SYBCA-(SEM-4)

public static void main(String[] args)


{
OverloadingDemo obj = new OverloadingDemo();

obj.sum(10, 10); // Calls the method with two integer parameters


obj.sum(10, 10, 10); // Calls the method with three integer parameters
obj.sum(10.5, 10.5); // Calls the method with two double parameters
}
}

Output

Sum of (a+b) is:: 20


Sum of (a+b+c) is:: 30
Sum of double (a+b) is:: 21.0

this Keyword

 Refers to the current object of the class.


 Use of this keyword
1. Distinguishing Instance Variables: Resolves ambiguity when instance variables
are shadowed by method parameters or local variables.

class Box {
int width;
Box(int width) {
this.width = width; // `this` refers to the instance variable
}
}

2. Calling Other Constructors: Used to call another constructor within the same
class.

class Box {
int width, height;
Box(int width) {
this(width, 10); // Calls the two-parameter constructor
}
Box(int width, int height) {
this.width = width;
this.height = height;
}
}

Sutex Bank College of Computer Applications & Science, Amroli |14


403: JAVA Programming Language | SYBCA-(SEM-4)

3. Returning the Current Object: Allows methods to return the current instance for
method chaining.

class Box {
int width;
Box setWidth(int width) {
this.width = width;
return this;
}
}
super Keyword

Refers to the immediate parent class object.

Use of super keyword

1. Accessing Parent Class Members: Access parent class fields or methods overridden in
the child class.

class Parent {
String name = "Parent";
}
class Child extends Parent {
String name = "Child";
void display() {
System.out.println(super.name); // Refers to the parent class field
System.out.println(name);
}
}

2. Calling Parent Class Methods: Used to invoke overridden methods in the parent class.

class Parent {
void display() {
System.out.println("Parent Method");
}
}
class Child extends Parent {
void display() {
super.display(); // Calls the parent class method
System.out.println("Child Method");
}
}

Sutex Bank College of Computer Applications & Science, Amroli |15


403: JAVA Programming Language | SYBCA-(SEM-4)

3. Calling Parent Class Constructors: Explicitly calls a parameterized or default constructor


of the parent class.

class Parent {
Parent(String message) {
System.out.println("Parent Constructor: " + message);
}
}
class Child extends Parent {
Child(String message) {
super(message); // Calls the parent class constructor
}
}

Key Differences

Feature this super


Refers To Current object Parent class object
Access Scope Members of the same class Members of the immediate
parent class
Constructor Usage Calls another constructor in the Calls a constructor of the parent
same class class
Overridden Method Not applicable Access overridden methods
Access

These keywords are essential for managing class hierarchies and handling object-specific
references in Java programming.

Difference between Method Overloading and Overriding

Aspect Overriding Overloading


Argument List The argument list must exactly match Overloaded methods MUST change
that of the overridden method. the argument list.
Return Type The return type must be the same as the Overloaded methods CAN change
overridden method in the super class. the return type.
Private and Final Private and final methods cannot be Private and final methods can be
Methods overridden. overloaded.
Occurs In Method overriding occurs in two classes Method overloading is performed
that have inheritance. within a class.
Binding Type Dynamic binding is used for overridden Static binding is used for
methods. overloaded methods.
Polymorphism Type Method overriding is the example of Method overloading is the example
run-time polymorphism. of compile-time polymorphism.

Sutex Bank College of Computer Applications & Science, Amroli |16


403: JAVA Programming Language | SYBCA-(SEM-4)

Static Keyword in Java

The static keyword in Java is primarily used for memory management. It allows variables and
methods to be shared across all instances of a class, meaning they belong to the class rather
than any particular object of the class. This is useful for creating constants or methods that
should be the same for every instance of the class.

Key Applications:

 Variables
 Methods
 Blocks
 Nested Classes

Characteristics of the static Keyword:

1. Shared Memory Allocation: Static variables and methods are allocated memory space
only once, shared by all instances of the class. This is useful for global states or shared
functionalities.
2. Accessible Without Object Instantiation: Static members can be accessed without
creating an instance of the class. This is ideal for utility functions and constants.
3. Associated with the Class: Static members are linked to the class itself, not to specific
objects. Changes to static members are reflected in all instances of the class.
4. Cannot Access Non-Static Members: Static methods cannot directly access non-static
members of the class as they are not associated with any particular instance.
5. Overloadable but Not Overridable: Static methods can be overloaded (same method
name with different parameters), but they cannot be overridden since they belong to
the class, not an object.
6. Access Before Instantiation: A static member can be accessed before any objects of its
class are created.

Static Blocks:

Static blocks are used for initialization of static variables and are executed once when the class
is loaded.

Example:

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

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

Sutex Bank College of Computer Applications & Science, Amroli |17


403: JAVA Programming Language | SYBCA-(SEM-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);
}}
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40

Static Variables:
Static variables are shared across all instances of the class, essentially acting as global variables
for that class.

Example:

class Test {
static int a = m1();
static {
System.out.println("Inside static block");
}
staticint m1() {
System.out.println("from m1");
return 20;
}

public static void main(String[] args) {


System.out.println("Value of a : " + a);
System.out.println("from main");
}}
Output:
from m1
Inside static block
Value of a : 20
from main

Static Methods:

Static methods are methods that belong to the class rather than any instance. They can only
access static variables and other static methods.
Restrictions:
1. Static methods can only directly call other static methods.
2. Static methods cannot access instance variables or methods directly.
3. Static methods cannot use this or super.

Sutex Bank College of Computer Applications & Science, Amroli |18


403: JAVA Programming Language | SYBCA-(SEM-4)

Example of Restrictions:

class Test {
static int a = 10;
int b = 20;
static void m1() {
a = 20;
System.out.println("from m1");
b = 10; // Error: Cannot access non-static field 'b'
m2(); // Error: Cannot call non-static method 'm2'
System.out.println(super.a); // Error: Cannot use 'super' in static context
}
void m2() {
System.out.println("from m2");
}
public static void main(String[] args) {
// Main method
}
}

Use Cases for Static Variables and Methods:

1. Static Variables: For properties that are common to all instances, like a shared constant
or counter.
2. Static Methods: For utility functions that don’t require object-specific data.

Example:

class Student {
String name;
int rollNo;
static String cllgName;
static int counter = 0;

Student(String name) {
this.name = name;
this.rollNo = setRollNo();
}
Static int setRollNo() {
counter++;
return counter;
}
static void setCllg(String name) {
cllgName = name;
}

Sutex Bank College of Computer Applications & Science, Amroli |19


403: JAVA Programming Language | SYBCA-(SEM-4)

void getStudentInfo() {
System.out.println("name : " + name);
System.out.println("rollNo : " + rollNo);
System.out.println("cllgName : " + cllgName);
}}
public class StaticDemo {
public static void main(String[] args) {
Student.setCllg("XYZ");

Student s1 = new Student("Alice");


s1.getStudentInfo();
Student s2 = new Student("Boby");
s2.getStudentInfo();
}}

Output:
name : Alice
rollNo : 1
cllgName : XYZ
name : Bob
rollNo : 2
cllgName : XYZ

Static Classes:

A class can only be declared static if it is a nested class. A static nested class does not require a
reference to the outer class and cannot access non-static members of the outer class.

Example of Static Nested Class:

Class Myclass {
private static String str = "Java programming language";

static class MyNestedClass {


public void disp() {
System.out.println(str);
}
}
public static void main(String args[]) {
Myclass.MyNestedClass obj = new Myclass.MyNestedClass();
obj.disp();
}}
Output:Java programming language

Sutex Bank College of Computer Applications & Science, Amroli |20


403: JAVA Programming Language | SYBCA-(SEM-4)

Advantages of Static Members:


1. Memory Efficiency: Static members are allocated memory only once, saving memory.
2. Improved Performance: Static members can be accessed more efficiently.
3. Global Accessibility: Static members can be accessed from anywhere in the program.
4. Constants: Static final variables can define constants used across the program.

static final double pi=3.14; //declare constant in java

5. Class-Level Functionality: Static methods can define functionality that doesn’t depend
on object state.

Abstraction in Java
- Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
- Another way, it shows only essential things to the user and hides the internal details,.
- for example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Ways to achieve Abstraction


- There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)

Abstract class in Java


 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
Example:
abstract class student1
{
abstract void result();
}
class student2 extends student1
{
void result()
{
System.out.println("It's My result");
}
}
class abstract_ex
{
public static void main(String s[])
{
student2 s1=new student2();
s1.result();
}}

Sutex Bank College of Computer Applications & Science, Amroli |21


403: JAVA Programming Language | SYBCA-(SEM-4)

Abstract class having constructor, data member and methods

Example:
abstract class salary
{
Int basic,da;
salary(int basic,int da) //Constructor
{
this.basic=basic;
this.da=da;
}
void greetings() //No abstract Method
{
System.out.println("Hello, Good morning all. I am Abstract Class");
}
abstract void ComputeSalary(); //Abstract Method
}

classGSalary extends salary


{
Int hra;
GSalary(int basic,int da,int hra) //Constructor
{
super(basic,da);
this.hra=hra;
}
void ComputeSalary() //Method Implementation of abstract class
{
System.out.println("Gross Salary:"+(basic+da+hra));
}
}
class abstract_ex1
{
public static void main(String s[])
{
GSalary sal=new GSalary(25000,1000,2500);
sal.greetings(); // call non abstract method
sal.ComputeSalary(); //call abstract method
}
}

Output:

Hello, Good morning all. I am Abstract Class


Gross Salary: 28500

Sutex Bank College of Computer Applications & Science, Amroli |22


403: JAVA Programming Language | SYBCA-(SEM-4)

Interfaces in Java

- An interface in Java is an abstract type used to define the behavior of a class.


- Java interfaces are primarily used to achieve abstraction and multiple inheritance.

- The key features of an interface are:


1. Abstraction: Interfaces define the behavior of a class without providing the
implementation details.
2. Multiple Inheritance: Unlike classes, a class can implement multiple interfaces, which
helps achieve multiple inheritances in Java.

Syntax of Java Interface


To declare an interface, use the interface keyword. Here’s the basic structure:

Interface InterfaceName {
// Declare constant fields (public, static, final by default)
// Declare abstract methods (public by default)
void method1(); // abstract method
void method2(); // abstract method
}

 Constant fields in interfaces are public, static, and final by default.


 Methods in an interface are abstract and public by default. They do not have a body.

Relationship between classes and interfaces


- As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Example:
interface A {
void display();
}
class B implements A{
public void display()
{
System.out.println("Hello");
}
}
class Interface_ex{
public static void main(String args[])
{
B obj = new B();
obj.display();
}}

Sutex Bank College of Computer Applications & Science, Amroli |23


403: JAVA Programming Language | SYBCA-(SEM-4)

Interface Implements in multiple Class


Example:
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello B");
}}
class C implements A
{
public void display()
{
System.out.println("Hello C");
}}
class MB
{
public static void main(String args[]){
B obj1 = new B();
obj1.display();
C obj2 = new C();
obj2.display();
}}

Multiple inheritance by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
asmultiple inheritance.

Example:
interface A{
void display();
}
interface B{
void show();
}
class C implements A,B{
public void display() {
System.out.println("Display method");
}
public void show(){
System.out.println("show method");
}
}

Sutex Bank College of Computer Applications & Science, Amroli |24


403: JAVA Programming Language | SYBCA-(SEM-4)

class MB
{
public static void main(String args[])
{
C obj = new C();
obj.display();
obj.show();
}
}

Output:
Hello
Welcome

Interface inheritance
A class implements an interface, but one interface extends another interface.
Example:
interface A
{
void show1();
}
interface B //one interface extends another interface
{
void show2();
}
interface C extends A, B {
void show3();
}

class demo implements C// one class implements another interface


{
public void show1()
{
System.out.println("From show1");
}
public void show2()
{
System.out.println("from show2");
}
public void show3()
{
System.out.println("From show3");
}

Sutex Bank College of Computer Applications & Science, Amroli |25


403: JAVA Programming Language | SYBCA-(SEM-4)

class MB
{
public static void main(String args[])
{
demo obj = new demo();
obj.show1();
obj.show2();
obj.show3();
}
}

Multiple Inheritance Using Interfaces


interface Exam{
void percent_cal();
}
class Student{
String name;
int roll_no,mark1,mark2;
Student(String n, int r, int m1, int m2) {
name=n;
roll_no=r;
mark1=m1;
mark2=m2;
}
void display() {
System.out.println ("Name of Student: "+name);
System.out.println ("Roll No. of Student: "+roll_no);
System.out.println ("Marks of Subject 1: "+mark1);
System.out.println ("Marks of Subject 2: "+mark2);
}}
class Result extends Student implements Exam{
Result(String n, int r, int m1, int m2) {
super(n,r,m1,m2);
}
public void percent_cal() {
int total=(mark1+mark2);
float percent=total/2;
System.out.println ("Percentage: "+percent+"%");
}
void display() {
super.display(); }}

Sutex Bank College of Computer Applications & Science, Amroli |26


403: JAVA Programming Language | SYBCA-(SEM-4)

classMultiple_Inheritance{
public static void main(String args[]) {
Result R = new Result("Sutex",12,93,84);
R.display();
R.percent_cal();
}}
Output:
Name of Student: Sutex
Roll No. of Student: 12
Marks of Subject 1: 93
Marks of Subject 2: 84
Percentage: 88.0%

Advantages of Interfaces in Java

 Security of Implementation: Interfaces allow us to define the behavior of a class


without worrying about the implementation details.
 Achieving Multiple Inheritance: While Java does not support multiple inheritance
through classes, interfaces can be used to achieve multiple inheritance by allowing a
class to implement multiple interfaces.
Differences between Interface and Abstract Class
Abstract class Interface
Abstract class can have abstract and non-abstract
Interface can have only abstract methods.
methods.
Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
Abstract class can have final, non-final, static and
Interface has only static and final variables.
non-static variables.
Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
An interface can extend another Java interface
An abstract class can extend another Java class.
only.
An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
A Java abstract class can have class members like
Members of a Java interface are public by default.
private, protected, etc.
Example: Example:
abstract class student{ interface A{
public abstract void result(); void display();
} }

Sutex Bank College of Computer Applications & Science, Amroli |27

You might also like