UNIT II
INHERITANCE, PACKAGES AND INTERFACES
Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner Classes.
Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –
Abstract Classes – final with Inheritance. Packages and Interfaces: Packages – Packages and Member Access
–Importing Packages – Interfaces.
PART A
1.List out ways of method overloading. AU ND.,2018
1. Changing the Number of Parameters.
2. Changing Data Types of the Arguments.
3. Changing the Order of the Parameters of Methods
2.Mention advantages of object as parameter.
1. Flexibility
2. Reusability of Code
3. Encapsulation
3.Differentiate inner class and static class AU.,AM 2018
S.No Inner Class(Non Static Nested Class) Static Nested Class
1. A non-static nested class is a class A static class i.e. created inside a
within another class. class is called static nested class in java.
2. It has access to members of the It cannot access non-static data
enclosing class (outer class) even if members and methods. It can be
they are declared private. It is accessed by outer class name.
commonly known as inner class.
3. It must instantiate the outer class No need to instantiate the outer class
first, in order to instantiate the inner
class.
4.Define Inheritance. AU AM 2019,2021
Inheritance is a process of deriving a new class from existing class, also called as
“extending a class”.
The class whose property is being inherited by another class is called “base
class”(or) “parent class” (or) “super class”.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 1 PREPARED BY DIVYA.A.S,AP/CSE
The class that inherits a particular property or a set of properties from the base class is called
“derived class” (or) “child class” (or) “sub class”.
5.Write inheritance syntax.
[access_specifier] class subclass_name extends superclass_name
// body of class
}
6.Mention types of inheritance . AU.,ND 2017,2016
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
7.Define Super Keyword. AU AM 2019
Super is a special keyword that directs the compiler to invoke the superclass members.
It is used to refer to the parent class of the class in which the keyword is used.
8.What are the ways to implement super keyword? AU ND2019
super keyword is used for the following three purposes:
1. To invoke super class constructor.
2. To invoke super class members variables.
3. To invoke super class methods.
9.Write syntax for super keyword. AU ND.,2017
Super Class Constructor Member Variable Member Methods
Syntax: Syntax: Syntax:
super(); or super.methodName();
super(parameter-list); super.membervariable;
10.Define Method Overridding and rules. AU AM.,2018,2021
The process of a subclass redefining a method contained in the superclass (with the same method
signature) is called Method Overriding.
Rules for Method Overriding:
1. The method must have the same name as in the parent class.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 2 PREPARED BY DIVYA.A.S,AP/CSE
2. The method must have the same parameter as in the parent class.
3. A method declared final cannot be overridden.
4. A method declared static cannot be overridden but can be re-declared.
5. Constructors cannot be overridden.
11.Differentiate Method Overloading and Method Overriding. AU ND.,2019
Method Overloading Method Overriding
Methods of the same class shares the same In sub class have the same method with
name but each method must have same name and exactly the same number
different number of parameters or and type of parameters and same return
parameters having different types and order. type as a super class
Method Overloading is to “add” or “extend” Method Overriding is to “Change” existing
more to method’s behavior. behavior of method.
12.What do you meant by Dynamic Dispatch Method?
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved
at run time, rather than compile time.
It allows objects to take on multiple forms, and one way it achieves this is through a mechanism
called dynamic method dispatch/ runtime polymorphism.
13.Write short notes on abstract class. AU AM.,2019
A class that is declared as abstract is known as abstract class. Abstract classes cannot be
instantiated, but they can be subclasses.
Syntax:
abstract class <class_name>
{
Member variables;
Concrete methods { }
Abstract methods();
}
14.Mention three uses of final keyword. AU AM.,2018
1. For declaring variable – to create a named constant. A final variable cannot be changed
once it is initialized.
2. For declaring the methods – to prevent method overriding. A final method cannot be
overridden by subclasses.
3. For declaring the class – to prevent a class from inheritance. A final class cannot be
inherited.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 3 PREPARED BY DIVYA.A.S,AP/CSE
15.Define packages. AU ND.,2020
A package can be defined as a group of similar types of classes, sub-classes, interfaces or
enumerations, etc.
Package created by package keyword.
Syntax:
Package package_name;
16.List Built in Packages. AU AM.,2021
java.io.*;
java.awt.*;
java.lang.*;
java.util.*;
java.sql.*;
17.What do you meant by interface? AU ND.,2019
An interface is a collection of method definitions (without implementations) and constant values.
It is a blueprint of a class.
It has static constants and abstract methods.
The keyword “interface” is used to define an interface.
Syntax:
access_specifier interface interface_name
{
Data_type variable=const;
Return_type method_name(parameter_list);
}
18. Difference between Class and Interface.
Class Interface
The class is denoted by a keyword class The interface is denoted by a keyword interface.
The class contains data members and methods The interfaces may contain data members and methods
with implementation. without implementation.
By creating an instance of a class can access you cannot create an instance of aninterface
class members.
The members of a class can be constant or The members of interfaces are alwaysdeclared as final
final
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 4 PREPARED BY DIVYA.A.S,AP/CSE
PART B
1.Explain Method overloading with an example. AU.,ND 2022
Method overloading is a feature in Java that allows a class to have more than one method with the
same name, as long as their parameter lists are different.
This can mean a difference in the number of parameters, the type of parameters, or both. Method
overloading is also known as compile-time polymorphism or static polymorphism/Early Binding.
Different Ways of Method Overloading in Java
1. Changing the Number of Parameters.
2. Changing Data Types of the Arguments.
3. Changing the Order of the Parameters of Methods
1. Changing the Number of Parameters
Method overloading can be achieved by changing the number of parameters while passing to
different methods.
Example Program: (noofarg,java)
class Product {
public int multiply(int a, int b)
{ int prod = a * b; Output:
return prod; } C:\java programs>javac noofarg.java
public int multiply(int a, int b, int c) C:\java programs>java noofarg
{ int prod = a * b * c; Product of the two integer value :2
return prod; Product of the three intger value :6
}}
class noofarg {
public static void main(String[] args)
{ Product ob = new Product();
int prod1 = ob.multiply(1, 2);
System.out.println( "Product of the two integer
value :" + prod1);
int prod2 = ob.multiply(1, 2, 3);
System.out.println( "Product of the three integer
value :" + prod2);
}}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 5 PREPARED BY DIVYA.A.S,AP/CSE
2. Changing Data Types of the Arguments
Methods can be overloaded with same name but have different parameter types.
Example Program: (diffdata.java)
class Product {
public int Prod(int a, int b, int c)
{ int prod1 = a * b * c; Output:
return prod1; } C:\java programs>javac diffdata.java
public double Prod(double a, double b, double c) C:\java programs>java diffdata
{ double prod2 = a * b * c;
return prod2; } Product of the three integer value :6
} Product of the three double value :6.0
class diffdata {
public static void main(String[] args)
{
Product obj = new Product();
int prod1 = obj.Prod(1, 2, 3);
System.out.println( "Product of the three
integer value :" + prod1);
double prod2 = obj.Prod(1.0, 2.0, 3.0);
System.out.println( "Product of the three
double value :" + prod2);
}
}
3. Changing the Order of the Parameters of Methods
Method overloading can also be implemented by rearranging the parameters of two or more
overloaded methods.
Example Program:
class Student {
public void StudentId(String name, int roll_no)
{ System.out.println("Name :" + name + " "+ "Roll-No Output:
:" + roll_no); } C:\javaprograms>javac
public void StudentId(int roll_no, String name) orderofparameter.java
{ System.out.println("Roll-No :" + roll_no + " "+ "Name C:\java programs>java
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 6 PREPARED BY DIVYA.A.S,AP/CSE
:" + name); } orderofparameter
} Name :Sandhiya Roll-No :1
class orderofparameter{ Roll-No :2 Name :Kamlesh
public static void main(String[] args)
{
Student obj = new Student();
obj.StudentId("Sandhiya", 1);
obj.StudentId(2, "Kamlesh");
}
}
Advantages of Method Overloading
Improves the Readability and reusability of the program.
Reduces the complexity of the program.
Perform a task efficiently and effectively.
2.Explain about Objects as Parameters with code. (7) AU.,ND 2018
Objects, like primitive types, can be passed as parameters to methods in Java.
When passing an object as a parameter to a method, a reference to the object is passed rather than a
copy of the object itself.
This means that any modifications made to the object within the method will have an impact on the
original object.
Example Program: (ObjectParameter.java)
class ObjectParameter {
private int roll_no;
private String name; Output:
public ObjectParameter(int roll_no, String name) { C:\javaprograms>javac
this.roll_no = roll_no; ObjectParameter.java
this.name= name; C:\java programs>java ObjectParameter
} Roll no: 20
// Method that takes an object as a parameter Name: World
public void display(ObjectParameter obj) { Roll no: 10
System.out.println("Roll no: " + obj.roll_no); Name: Hello
System.out.println("Name: " + obj.name);
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 7 PREPARED BY DIVYA.A.S,AP/CSE
public static void main(String[] args) {
ObjectParameter obj1 = new ObjectParameter(10, "Hello");
ObjectParameter obj2=new ObjectParameter(20, "World");
// Passing obj2 as a parameter to the displayAttributes
method of obj1
obj1.display(obj2);
// Passing obj1 as a parameter to the displayAttributes
method of obj2
obj2.display(obj1);
}}
Advantages of Passing an Object as a Parameter
1. Flexibility
2. Reusability of Code
3. Encapsulation
3.Explain about Returning Objects with java code. (6) AU.,ND 2018
Similar to returning primitive types, Java methods can also return objects.
A reference to the object is returned when an object is returned from a method, and the calling method
can use that reference to access the object.
Example Program: (ObjectParameter.java)
class ObjectReturn {
int a;
ObjectReturn(int i) { a = i; } Output:
ObjectReturn incrByTen() C:\java programs>javac
{ ReturnObject.java
ObjectReturn temp=new ObjectReturn(a + 10); C:\java programs>java ReturnObject
return temp; } ob1.a: 2
} ob2.a: 12
public class ReturnObject{
public static void main(String args[])
{
ObjectReturn ob1 = new ObjectReturn(2);
ObjectReturn ob2;
ob2 = ob1.incrByTen();
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 8 PREPARED BY DIVYA.A.S,AP/CSE
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
}}
STATIC, NESTED AND INNER CLASSES
4.Write short notes on Non Static Nested Classes.
In Java, it is possible to define a class within another class, such classes are known as nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members of its enclosing class, including private members. But the
enclosing class does not have access to the member of the nested class.
A nested class is also a member of its enclosing class.
Nested classes are divided into two categories:
1. static nested class: Nested classes that are declared static are called static nested classes.
2. inner class: An inner class is a non-static nested class.
1. Inner Class/Non-Static Nested ClassInner Class
A non-static nested class is a class within another class.
It has access to members of the enclosing class (outer class) even if they are declared private. It is
commonly known as inner class.
It must instantiate the outer class first, in order to instantiate the inner class.
Syntax of Inner class:
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Instantiating an Inner Class: Two Methods:
1. Instantiating an Inner class from outside the outer class:
To instantiate an instance of an inner class, you must have an instance of the outer
class.
Syntax:
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 9 PREPARED BY DIVYA.A.S,AP/CSE
OuterClass.InnerClass objectName=OuterObj.new InnerClass();
2. Instantiating an Inner Class from Within Code in the Outer Class:
From inside the outer class instance code, use the inner class name in the
normal way:
Syntax:
InnerClassName obj=new InnerClassName();
Advantage of Java inner classes
1. Access all the members (data members and methods) of the outer class, including private.
2. More readable and maintainable code.
3. Requires less code to write.
5.Write a java program for Non Static Nested Classes.
Example Program: (innerouterclass.java)
class TestMemberOuter1
{
private int data=30;
class Inner Output:
{ C:\java programs>
void msg() javac innerouterclass.java
{
System.out.println("data is "+data);
} C:\java programs>java innerouterclass
} data is 30
}
class innerouterclass
{
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}}
Example Program: (innerclass.java)
class localInner1
{
private int data=30;//instance variable
Output:
void display()
{ C:\java programs>javac innerclass.java
int value=50;
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 10 PREPARED BY DIVYA.A.S,AP/CSE
class Local
{ C:\java programs>java innerclass
void msg()
30
{
System.out.println(data); 50
System.out.println(value);
}
}
Local l=new Local();
l.msg();
}
}
class innerclass
{
public static void main(String args[])
{
localInner1 obj=new localInner1();
obj.display();
}
}
6.Write a Program for Static nested class.
A static class i.e. created inside a class is called static nested class in java.
It cannot access non-static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
Example Program: (staticclass.java)
class TestOuter1
{
static int data=30; Output:
static class Inner C:\java programs>javac staticclass.java
{ C:\java programs>java staticclass
void msg() data is 30
{
System.out.println("data is "+data);
}}}
class staticclass
{
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 11 PREPARED BY DIVYA.A.S,AP/CSE
public static void main(String args[])
{
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}}
INHERITANCE
7.Explain in detail about the basics of inheritance and elaborate on any two inheritance mechanisms
in java. AU.,AM 2023
Inheritance is a process of deriving a new class from existing class, also called as
“extending a class”. When an existing class is extended, the new (inherited) class has all
the properties and methods of the existing class and also possesses its own
characteristics.
The class whose property is being inherited by another class is called “base class”(or)
“parent class” (or) “super class”.
The class that inherits a particular property or a set of properties from the base
classis called “derived class” (or) “child class” (or) “sub class”.
Subclasses of a class can define their own unique behaviors and yet share some of the
same functionality of the parent class.
Advantages
Reusability of Code
Effort and Time Saving
Increased Reliability
“extends” KEYWORD:
The extends keyword is used to inherit a class from existing class.
Syntax:
[access_specifier] class subclass_name extends superclass_name
// body of class
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 12 PREPARED BY DIVYA.A.S,AP/CSE
Characteristics of Class Inheritance:
1. A class cannot be inherited from more than one base class.
2. Sub class can access only the non-private members of the super class.
3. Private data members of a super class are local only to that class.
4. Protected features in Java are visible to all subclasses as well as all other classes in the same
package.
TYPES OF INHERITANCE
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 13 PREPARED BY DIVYA.A.S,AP/CSE
1. SINGLE INHERITANCE
The process of creating only one subclass from only one super class is known as
Single Inheritance.
Only two classes are involved in this inheritance.
The subclass can access all the members of super class.
Example Program: (Main.java)
class A
{
void show()
{
System.out.println("Class A");
}}
class B extends A
{ Output:
void disp() C:\java programs>javac Main.java
{
C:\java programs>java Main
System.out.println("Class B");
}}
class Main Class A
{ Class B
public static void main(String args[])
{
B b=new B();
b.show();
b.disp();}}
2. MULTILEVEL INHERITANCE
The process of creating a new sub class from an already inherited sub class is known as Multilevel
Inheritance.
Multiple classes are involved in inheritance, but one class extends only one.
The lower most subclass can make use of all its super classes
members.Example Program: (Main.java)
import java.io.*;
class A
{
void show()
{
System.out.println("Class A");
} Output:
} C:\java programs>javac Main.java
class B extends A
C:\java programs>java Main
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 14 PREPARED BY DIVYA.A.S,AP/CSE
{ Class A
void disp() Class B
{
Class C
System.out.println("Class B");
}
}
class C extends B
{
void display()
{
System.out.println("Class C");
}
}
class Main
{
public static void main(String args[])
{
C c=new C();
c.show();
c.disp();
c.display();
}
}
3. HIERARCHICAL INHERITANCE
The process of creating more than one sub classes from one super class is called Hierarchical
Inheritance.
Example Program: (Main.java)
class A
{
void show()
{
System.out.println("Class A");
}}
class B extends A
{ Output:
void disp() C:\java programs>javac Main.java
{
C:\java programs>java Main
System.out.println("Class B CHILD OF A");
}} Class A
class C extends B Class B CHILD OF A
{ Class A
void display()
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 15 PREPARED BY DIVYA.A.S,AP/CSE
{ Class C CHILD OF A
System.out.println("Class C CHILD OF A");
}}
class Main
{
public static void main(String args[])
{
B b=new B();
b.show();
b.disp();
C c=new C();
c.show();
c.display();
}}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritances is not supported in java.
Consider a scenario where A, B and C are three classes.
The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be ambiguity to
call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit
2 classes. So whether you have same method or different, there will be compile time error now.
8.Discuss about Super Keyword with Java program. (8)AU.,ND 2018.
Super is a special keyword that directs the compiler to invoke the superclass members. It is used to
refer to the parent class of the class in which the keyword is used.
super keyword is used for the following three purposes:
1. To invoke super class constructor.
2. To invoke super class members variables.
3. To invoke super class methods.
1. Invoking a super class constructor:
Super as a standalone statement(ie. super()) represents a call to a constructor of the super class.
A subclass can call a constructor method defined by its super class by use of the following form of
super:
Syntax:
super(); or
super(parameter-list);
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 16 PREPARED BY DIVYA.A.S,AP/CSE
Here, parameter-list specifies any parameters needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass constructor.
2. Invoking a superclass members (variables and methods):
i. Accessing the instance member variables of the superclass:
Syntax:
super.membervariable;
ii. Accessing the methods of the superclass:
Syntax:
super.methodName();
This call is particularly necessary while calling a method of the super class that is overridden in the
subclass.
If a parent class contains a finalize() method, it must be called explicitly by the derived class’s
finalize() method.
Example Program: (Main.java)
class A // super class
{
int i;
A(String str) //superclass constructor
{
System.out.println(" Welcome to "+str);
}
Output:
void show() //superclass method
{ C:\java programs>javac UseSuper.java
System.out.println(" Thank You!"); C:\java programs>java UseSuper
}
Welcome to Java Programming
}
class B extends A i in superclass : 1
{ i in subclass : 2
int i; // hides the superclass variable 'i'. Thank You!
B(int a, int b) // subclass constructor
{
super("Java Programming");
super.i=a;
i=b;
}
void show()
{
System.out.println(" i in superclass : "+super.i);
System.out.println(" i in subclass : "+i);
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 17 PREPARED BY DIVYA.A.S,AP/CSE
super.show(); // invoking superclass method
}
}
public class UseSuper {
public static void main(String[] args) {
B objB=new B(1,2);
objB.show();
}
}
9.Explain Method overriding with an example.(5) AU.,ND 2023
The process of a subclass redefining a method contained in the superclass (with the same method
signature) is called Method Overriding.
Rules for Method Overriding:
1. The method must have the same name as in the parent class.
2. The method must have the same parameter as in the parent class.
3. A method declared final cannot be overridden.
4. A method declared static cannot be overridden but can be re-declared.
5. Constructors cannot be overridden.
Advantage of Method Overriding:
Method Overriding is used to provide specific implementation of a method.
Method Overriding is used for Runtime Polymorphism
Example Program: (methodoverride.java)
class animal
{
void sound()
{
System.out.println("Animal Sound");
}
}
Output:
class dog extends animal
{ C:\java programs>javac methodoverride.java
void sound() C:\java programs>java methodoverride
{
Animal Sound
super.sound();
System.out.println("Barking Sound"); Barking Sound
}
}
class methodoverride
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 18 PREPARED BY DIVYA.A.S,AP/CSE
{
public static void main(String args[])
{
dog d=new dog();
d.sound();
}
}
10.Explain about Dynamic Method Dispatch with code fragments in java.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time.
It allows objects to take on multiple forms, and one way it achieves this is through a mechanism
called dynamic method dispatch/ runtime polymorphism.
When an overridden method is called by a reference, java determines which version of that method to
execute based on the type of object it refer to.
Advantages:
It is a powerful feature because it allows flexibility to write code.
Promotes code reusability and modularity
By allowing objects to take on multiple forms.
Example Program: (Dispatch.java)
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 C extends A
{
Output:
void callme() {
System.out.println("Inside C's callme method"); C:\java programs>javac Dispatch.java
}} C:\java programs>java Dispatch
class Dispatch Inside A's callme method
{
public static void main(String args[]) Inside B's callme method
{ Inside C's callme method
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 19 PREPARED BY DIVYA.A.S,AP/CSE
A a=new A(); //object of type A
B b=new B(); //object of type B
C c=new C(); //object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
// dynamic method dispatch
r.callme(); // calls A’s version of callme()
r = b; // r refers to an B object
r.callme(); // calls B’s version of callme()
r = c; // r refers to an C object
r.callme(); // calls C’s version of callme()
}
}
11.With an example explain the use of Abstract classes in Java. AU.,AM 2024
Abstraction:
Abstraction is a process of hiding the implementation details and showing only the essential features
to the user.
Ex: sending sms, you just 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 Classes:
A class that is declared as abstract is known as abstract class. Abstract classes cannot be instantiated,
but they can be subclasses.
Syntax:
abstract class <class_name>
{
Member variables;
Concrete methods { }
Abstract methods();
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 20 PREPARED BY DIVYA.A.S,AP/CSE
Abstract Methods:
A method that is declared as abstract and does not have implementation is known as abstract method.
It acts as placeholder methods that are implemented in the subclasses.
If a class contains at least one abstract method then compulsory should declare a class as abstract
Syntax:
abstract class classname
{
abstract return_type <method_name>(parameter_list);//no braces
{
//no function body
}
……..
}
Ex: Write a Java program to create an abstract class named Shape that contains 2 integers and an
empty method named PrintArea(). Provide 3 classes named Rectangle, Triangle and Circle such that
each one of the classes extends the class Shape. Each one of the classes contain only the method
PrintArea() that prints the area of the given shape. (AU ND 2019)
Example Program: (Dispatch.java)
abstract class shape
{
int x, y;
abstract void printArea();
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 21 PREPARED BY DIVYA.A.S,AP/CSE
class Rectangle extends shape
{
void printArea()
{
System.out.println("Area of Rectangle is " + x * y);
} Output:
}
class Triangle extends shape
{ C:\java programs>javac abs.java
void printArea() C:\java programs>java abs
{
Area of Rectangle is 200
System.out.println("Area of Triangle is " + (x * y) / 2);
} Area of Triangle is 525
} Area of Circle is 12
class Circle extends shape
{
void printArea()
{
System.out.println("Area of Circle is " + (22 * x
* x) / 7);
}
}
class abs
{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
r.printArea();
Triangle t = new Triangle();
t.x = 30;
t.y = 35;
t.printArea();
Circle c = new Circle();
c.x = 2; c.printArea();
}
}
12.Explain about inheritance with final keywords. Outline Code fragments.
Final is a keyword or reserved word in java used for restricting some functionality.
It can be applied to member variables, methods, class and local variables in Java.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 22 PREPARED BY DIVYA.A.S,AP/CSE
Final keyword has three uses:
1. For declaring variable – to create a named constant. A final variable cannot be changed once it is
initialized.
2. For declaring the methods – to prevent method overriding. A final method cannot be overridden
by subclasses.
3. For declaring the class – to prevent a class from inheritance. A final class cannot be inherited.
1. Final Variable:
Any variable either member variable or local variable modified by final keyword is called final
variable.
The final variable can be assigned only once.
The value of the final variable will not be changed during the execution of the program.
If an attempt is made to alter the final variable value, the java compiler will throw an error
message.
Syntax:
final data_type variable_name = value;
Example:
final int PI=3.14;
Example Program: (Finalvar.java)
class Bike Output:
{ C:\java programs>javac Finalvar.java
final int speedlimit=90;//final variable
Finalvar.java:6: error: cannot assign a value to final
void run( )
{ variable speedlimit
speedlimit=400; speedlimit=400;
}}
^
class Finalvar
{ 1 error
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
2.Final Methods:
Final keyword can also be applied to methods.
A java method with final keyword is called final method and it cannot be overridden in sub-
class.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 23 PREPARED BY DIVYA.A.S,AP/CSE
If a method is defined with final keyword, it cannot be overridden in the subclass and its
behaviour should remain constant in sub-classes.
Syntax:
final return_type function_name(parameter_list)
{
// method body
}
Example Program: (Finalmthd.java)
class Bike Output:
{ C:\java programs>javac Finalmthd.java
final void run()
Finalmthd.java:10: error: run() in Honda cannot
{
System.out.println("running"); override run() in Bike
} void run()
}
^
class Honda extends Bike
{ overridden method is final
void run() 1 error
{
System.out.println("running safely with
100kmph");
}
}
class Finalmthd
{
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
3. Final Classes:
Java class with final modifier is called final class in Java and they cannot be sub-classed
or inherited.
Syntax:
final class class_name
{
// body of the class
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 24 PREPARED BY DIVYA.A.S,AP/CSE
Example Program: (Finalclass.java)
final class Bike Output:
{ C:\java programs>javac Finalclass.java
}
Finalclass.java:4: error: cannot inherit from
class Honda1 extends Bike
{ final Bike
void run() class Honda1 extends Bike
{
^
System.out.println("running safely with
100kmph"); 1 error
}
}
class Finalclass
{
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
PACKAGES
13.What is a package?Explain in detail about how the packages provide access control to various
categories of visibility for class members. AU.,AM 2023
What are the advantages of using packages?(5)AU.,ND 2022
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form,
Advantage of Java Package
1) To categorize the classes and interfaces so that they can be easily maintained.
2) Provides access protection.
3) Removes naming collision.
Syntax:
package package_name.[sub_package_name];
public class classname
{
……..
……..
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 25 PREPARED BY DIVYA.A.S,AP/CSE
Member Access Control
Java provides several access modifiers to control access to classes, methods, and fields:
1.Public: The member is accessible from any other class.
public class MyClass {
public void myMethod() {
// Accessible everywhere
}
}
2.Protected: The member is accessible within its own package and by subclasses.
public class MyClass {
protected void myMethod() {
// Accessible within package and subclasses
}
}
3.Default (Package-Private): If no access modifier is specified, the member is accessible only within its
own package.
class MyClass {
void myMethod() {
// Accessible within package
}
}
4.Private: The member is accessible only within its own class.
public class MyClass {
private void myMethod() {
// Accessible only within this class
}
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 26 PREPARED BY DIVYA.A.S,AP/CSE
Example Program: (FirstClass.java)
package MyPack;
public class FirstClass
{
public String i="I am public variable";
protected String j="I am protected variable";
private String k="I am private variable";
String r="I dont have any modifier";
}
Example Program: (SecondClass.java) Output:
package MyPack2; C:\java programs>javac SecondClass.java
import MyPack.FirstClass; C:\java programs>java SecondClass
class SecondClass extends FirstClass { I am public variable
void method() I am protected variable
{
System.out.println(i);
System.out.println(j);
System.out.println(k);
// Error: k has private access in FirstClass
System.out.println(r);
/* Error: r is not public in FirstClass
cannot be accessed from outside package */
}
public static void main(String arg[])
{
SecondClass obj=new SecondClass();
obj.method();
}
}
14.Write short notes on In Built Package with example.
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form,
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 27 PREPARED BY DIVYA.A.S,AP/CSE
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.
Some of the commonly used built-in packages are:
java.lang: Contains language support classes. This package is automatically imported.
java.io: Contains classes for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for
implementing the components for graphical user interfaces (like button , ;menus etc).
java.net: Contain classes for supporting networking operations.
Example Program: (MyClass.java)
import java.util.Scanner; Output:
class MyClass { C:\java programs>javac MyClass.java
public static void main(String[] args) { C:\java programs>java MyClass
Scanner myObj = new Scanner(System.in); Enter username
System.out.println("Enter username"); Username is: divya
String userName = myObj.nextLine();
System.out.println("Username is: " +
userName);
}
}
java.util is a package, while Scanner is a class of the java.util package.
Advantage of Java Package
4) To categorize the classes and interfaces so that they can be easily maintained.
5) Provides access protection.
6) Removes naming collision.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 28 PREPARED BY DIVYA.A.S,AP/CSE
15.What is user defined package?How to create and import a user defined package?Explain with
example. AU.,AM 2024
(OR)Illustrate how to add classes in a package and how to access these classes in another package.
(8)AU.,ND 2022
User-defined packages:
These are the packages that are defined by the user.
First we create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being the package names.
1. Creating User Defined Packages:
Java package created by user interface are known as user-defined packages.
When creating a package, you should choose a name for the package.
The package statement should be the first line at the top of every source file
There can be only one package statement in each source file
Syntax:
package package_name.[sub_package_name];
public class classname
{
……..
……..
}
Steps involved in creating user-defined package:
1. Create a directory which has the same name as the package.
2. Include package statement along with the package name as the first statement in the
program.
3. Write class declarations.
4. Save the file in this directory as “name of class.java”.
5. Compile this file using java compiler.
2. Importing Packages/Accessing A Package
The import keyword is used to make the classes and interface of another package accessible to
the current package.
Syntax:
import package1[.package2][.package3].classname or *;
There are three ways to access the package from outside the package.
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 29 PREPARED BY DIVYA.A.S,AP/CSE
1. import package.*;
2. import package.classname;
3. fully qualified name.
I. Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
II. Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
III. Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import.
But you need to use fully qualified name every time when you are accessing the class or
interface.
Example Program: (FactorialClass.java)
package Factorial;
public class FactorialClass
{
public int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1); } }
import java.lang.*; Output:
// using import package.* C:\java programs>javac ImportClass.java
import pack.Factorial.FactorialClass; C:\java programs>java ImportClass
// using import package.subpackage.class; Enter a Number:
import java.util.Scanner; 5
public class ImportClass Hello! Good Morning!
{ Factorial of 5 = 120
public static void main(String[] arg) Power(5,2) = 25.0
{
int n;
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 30 PREPARED BY DIVYA.A.S,AP/CSE
Scanner in=new Scanner(System.in);
System.out.println("Enter a Number: ");
n=in.nextInt();
pack.greeting p1=new pack.greeting();
// using fully qualified name
p1.greet();
FactorialClass fobj=new FactorialClass();
System.out.println("Factorial of "+n+" = "+fobj.fact(n));
System.out.println("Power("+n+",2)="+Math.pow(n,2));
}
}
INTERFACES
16.What is an interface?How to define an interface?How one or more classes can implement an
interface?Outline with code fragments.AU.,ND 2023
An interface is a collection of method definitions without implementations and constant values.
It is a blueprint of a class.
It has static constants and abstract methods.
The keyword “interface” is used to define an interface.
Interface Uses:
It is used to achieve fully abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling.
Advantage:
Writing flexible and maintainable code.
Declaring methods that one or more classes are expected to implement.
Syntax:
access_specifier interface interface_name
{
Data_type variable=const;
Return_type method_name(parameter_list);
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 31 PREPARED BY DIVYA.A.S,AP/CSE
Understanding relationship between classes and interfaces
‘
Implementing Interfaces (“implements” keyword):
Once an interface has been defined, one or more classes can implement that interface by using
implements keyword to implement an interface.
Syntax:
[access_specifier] class class_name [extends superclassName] implements
interface_name1, interface_name2…
{
//implementation code and code for the method of the interface
}
Rules:
1) If a class implements an interface, then it must provide implementation for all the methods defined
within that interface.
2) A class can implement more than one interfaces by separating the interface names with comma(,).
3) A class can extend only one class, but implement many interfaces.
4) An interface can extend another interface, similarly to the way that a class can extend another
class.
5) If a class does not perform all the behaviors of the interface, the class must declare itself as
abstract.
1. Single Interface With Multiple Classes:
EXAMPLE PROGRAM: (Main.java) Output:
interface Animal { C:\java programs>javac Main.java
public void animalSound(); // No Function body
C:\java programs>java Main
public void character(); // No Function body
} The pig says: wee wee
class Pig implements Animal { Piglet
public void animalSound() {
The Dog says: wow wow
System.out.println("The pig says: wee wee");
} Scooby
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 32 PREPARED BY DIVYA.A.S,AP/CSE
public void character() {
System.out.println("Piglet"); }
}
class Dog implements Animal {
public void animalSound() {
System.out.println("The Dog says: wow wow");
}
public void character() {
System.out.println("Scooby");
}}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.character();
Dog myDog = new Dog();
myDog.animalSound();
myDog.character();
}}
17.Write a java program to implement one or more interfaces in class?AU.,ND 2019
Multiple Interface :
EXAMPLE PROGRAM: Output:
(multipleinterface.java) C:\javaprograms>javac multipleinterface.java
interface Printable{
C:\java programs>java multipleinterface
void print();
} Hello
interface Showable{ Welcome
void show();
}
class A implements Printable,Showable
{ public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}
class multipleinterface
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show(); }
}
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 33 PREPARED BY DIVYA.A.S,AP/CSE
18.Write Short notes an extending interfaces. AU.,ND 2019
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class.
The extends keyword is used to extend an interface, and the child interface inherits the methods
of the parent interface.
Syntax:
[accessspecifier] interface InterfaceName extends interface1, interface2,…..
{
Code for interface
}
EXAMPLE PROGRAM: (extendsinterface.java) Output:
interface Printable C:\javaprograms>javac
{void print(); extendsinterface.java
}
C:\java programs>java extendsinterface
interface Showable extends Printable
{ Hello
void show(); Welcome
}
class TestInterface implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
}
class extendsinterface
{public static void main(String args[])
{
TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}
-----------------------------------@@@@@@@@@@@@@@@--------------------------------------------------------
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 34 PREPARED BY DIVYA.A.S,AP/CSE
ADDITIONAL SUGGESTED QUESTIONS
1. What is a package?Explain in detail about how the packages provide access AU.,AM 2023
control to various categories of visibility for class members.
2. Explain in detail about the basics of inheritance and elaborate on any two AU.,AM 2023
inheritance mechanisms in java.
3. Outline method overloading and method overriding in Java with code AU.,ND 2023
fragments.
4. What is an interface? How to define an interface? How one or more classes AU.,ND 2023
can implement an interface? Outline with code fragments.
5. Write a java program for library interface with drawbook(),returnbook() and AU.,ND 2022
checkstatus() methods (8)
6. Explain Method overloading with an example.(5) AU.,ND 2022
7. What are the advantages of using packages?(5) AU.,ND 2022
8. Illustrate how to add classes in a package and how to access these classes in AU.,ND 2022
another package.(8)
9. With an example explain the use of Abstract classes in Java. AU.,AM 2024
10. What is user defined package? How to create and import a user defined AU.,AM 2024
package? Explain with example.
-----------------------------------@@@@@@@@@@@@@@@--------------------------------------------------------
SRRCET/CSE/III SEM/CS3391_OOPS_UNIT II 35 PREPARED BY DIVYA.A.S,AP/CSE