Oops Unit 2
Oops Unit 2
PART-1
2 UNIT
Inheritance, Interfaces
and Packges
Inheritance : Super Classes, Sub Classes, Protected Members,
Constructors in Sub Classes, Object Class,
Abstract Classes and Methods.
Questions-Answers
Answer
Following are the differeut forms of inheritance in Java: Class B
1. Single Inheritance :
from only one
i. In single inheritance, a class is allowed to inherit only. Class C
class, i.e., one sub class is inherited by one base class
ii Fig. 2.2.1l is a diagram illustrating single inheritance : Fig. 223.
V.
In Fig. 2.2.3,Class Binherits the members or methods of Class A.
Class A Vi. Class C inherits the members of Class B.
vü. Therefore, Class A is the parent class of Class B and Class B is the
parent of Class C.
Class B viü. Hence, Class C implicitly inherits the properties of Class A along
with Class B.
Fig. 2.2.1. 4 Hierarchical Inheritance :
ii. In Fig. 2.2.1, Class A is a parent class and Class B is a child class. In this type of inheritance, more than one sub class is inherited
Class B inherits all the properties of the Class A. from a single base class, i.e, more than one derived class is
Multiple Inheritance (through interfaces) : from a single base class.
created
i. In multiple inheritance a class can inherit from more than one This creates a bierarchy of classes with multiple subclasses at the
classes, i.e., one sub class is inherited from more than one base same level.
classes.
. Java does not support multiple inheritance of classes, but it does
iüi. Each subelass inherits properties and methods from the same
superclass.
support nmultiple inheritance through interfaces.
An interface can be implemented by multiple classes, allowing them iv. Fig. 2.2.4 is a diagram illustrating hierarchical
inheritance :
toinherit properties and methods from the same interface.
Class A
iv. Fig.2.2.2 is a diagram illustrating multiple inheritance:
Class A Class B
Class B Class C
Answer 3 There can be only abstract methods in the Java interface, not method
The inal' keyword is apowerful tool for creating constants, enforcing body.
1 programs, It is used to achieve abstraction and multiple inheritance in Java.
immutability, and preventing unexpected behavior indava 4
used with parameters to indicate that thev 5 There are mainly three reasons to use interface
2 Thefinal' keyword can be method.
It is used to achieve abstraction.
cannot be modified withina i.
a cateh block to ensure that an By inter face, we can support the functionality of
multiple
3 The final' keyword can also be used with ii
exception iscAught and not rethrown. inheritance.
following three ways: iii. It can be used to achieve loose coupling.
4 We can use final key word in keyword indieot keyword.
Constants:Whon usod with avariable, the inal' 6 An interface is declared by using the înterface'
changed after it is initiali methods in an interface are
that the variable's value cannot be
that can be Used throughout th
7 It provides total abstraction; means all the static and
This creates a constant variable changes. declared with the empty body, and all the fields are public,
the risk of aceidental
Preventwithout
ii. program inheritance: When used with a class, the "final' keyword final by default.
must implement all the methods
cannot be subcla88ed or
8 A class that implements an interface
indicates that the class inherited.
modifying the behavio.
This declared in the interface.
prevents other classes from Syntax:
implementation of the final class.
overriding: When used with a method, intorface <interface_name>
iii. Prevent method
that the method cannot be the
'final' keyword
subclasses. This
indicates
ensure that the method's behavioroverridden
by
remains I/declare constant fields
program.
consistent throughout the / declare methods that abstract
/ by default.
2-11 B(MCA-Sem-2) 2-12 B(MCA-Sem-2) Inheritance, Interfaces and Packages
Object Oriented Programming
how to Answer
interface ? With an example explain Simple Interface:
Que 2.10. What is A
interface. A simple interface in Java is an interface that is deciared in its own
define and implement OR
1.
separate file.
example.
implemented in Java with an Here's an example of asimple interface:
Outline how interfaces are 2.
public interface Animal
and/or
Answer defines a set of methods public void eat();
interface is a contract that
1 In Java, an implement. public void sleep0;
constants that a class must an implementation
provide
Aclass that implements an interface agrees to
2
for all the methods
declared in the interface. In this example, Animal' is a simple interface that declares two methods,
implements keyword, 'eat()' and 'sleep(0.
interface in Java, you use the
3 To implement an interface. Any class that implements the 'Animal' interface must provide an
followed by the name of the 4.
implementation for both of these methods.
4. Here's an example: B. Nested Interface:
public interface Animal { declared inside another
1 A nested interface in Java is an interface that is
public void eat); class or interface.
public void sleep(0; 2 Nested interfaces are useful for organizing related interfaces.
3 Here's an example of a nested interface :
Animal {
public class Dog implements public class OuterClass {
public void eat(){ public interface InnerInterface f
System.out.println("Dog is eating"); public void doSomething ):
Answer
Que 2.14. Describe extending interfaces in Java with example.
S.No. Feature Classes Interfaces Answer
1. Definition Ablueprint for creating A contract for 1 An interface can extend another interface, which means that the child
objects. implementing behavior. interface inherits all the methods from the parent interface and can add
additional methods of its own. This is known as extending interfaces.
2 Fields Can contain instance andCannot contain instance or One interface can inherit another by use of the keyword 'extends'.
static fields. static fields. 2
3 Following is an example :
3 Methods Can contain concrete and Can only contain abstract public interface Animal{
abstract methods. methods. m
public void eat();
4 Access Can use public, protected, Can use only public and
modifiers private, and default. default access modifiers. public void sleep0;
}
5. Constructor Can have constructors. Cannot have constructors. public interface Pet extends Animal
6 Inheritance Can be extended by otherCan be implemented by public void play);
classes. classes or extended by
other interfaces.
7. Multiple Does not support multiple Supports multiple
4 In the above example, we have two îmterfaces: 'Animal' and 'Pet.
inheritance inheritance. inheritance through 5. Pet' extends 'Animal, which means it inherits the 'eat()' and »sleep(
multiple interface methods from 'Animal'.
|implementation. 6 In addition to the methods inherited from 'Animal, Pet' also adds anew
method called 'play)'.
Que 2.13. Differentiate betweenabstract class and interface. 7 Any class that ìmplements the Pet' interface must provide an
implementation for allthree methods: "eat(), sleepo and jplay().
Answer
Que 2.15.Explain object cloning in Java. Give its advantages and
S.No. Abstract Class Interface disadvantages.
1 Abstract class can have Interface can have only abstraot
abstract and non-abstract methods. Answer
methods. 1 Object cloning in Java is the process of ereatinga duplicate of an existing
2 Abstract class doesn't supportIntertace supports multinle object.
multiple inheritance. inheritance. 2 In Java, object cloning can be performed using the 'clone()' method,
3 Abstract class can have final, Interface has only which is defined in the Object' class.
non-final, static and non- variables. static and final 3 To enable cloning of an object, the class must implement the
static variables. Cloneable interface, which is a marker interface indicating that the
object can be cloned.
Abstract class can provide Interface can't
fa class attempts to clone an object without implementing the Cloneable'
4
the implementation of implementation of provide 4
interface. abstract class.the 5.
interface, it will throw a CloneNotSupportedException'.
Syntax of the clone() method :
5 The abstract keyword is usedThe interface
to declare abstract class. declare interfacekeeyword is used to protected Object clone() throws Clone NotSupportedException
-16B(MCA-Sem-2) Inheritance, Interfaces and Packages
Object Oriented Programming 2-15B (MCA-Sem-2)
Advantages of object cloning :
1. Object cloning provides away to create copies of objects without requiring
Questions-Answers
the original object to be modified. TongAnswer Type and Medium Answer Type Questions
2
Object cloning can improve performance in situations where it is
expensive to create a new object from scratch.
Disadvantages oB object cloning : Que 2.17. Explain in detail Ithe term package in Java.
1
Object cloning can be error-prone and can lead to unexpected behavior
if not implemented correctly.
Answer
2.
Object cloning can be slow for large objects or objects with complex In Java, a package is a way to group related classes, interfaces,
state. 1
enumerations, and annotations.
3.
Cloned objects can have references to the same objects as the original Apackage is a collection ofrelated classes that are stored together in a
object, which can lead to unexpected side effects if the referenced objects 2.
are modified. single directory or folder.
3. The main purpose of packages in Java is to provide a way to organize
Que 2.16. Explain about inner classes in Java. code and prevent naming conflicts.
and manage
Answer 4 By organizing classes into packages, it is easier to locate
conflicts between
code, and it also reduces the likelihood of naming
1 Inner classes in Java are classes that are defined inside another class, classes that have the same name.
beginning of a
2. Inner classes are used when a class needs to be closely tied to its 5. Packages are defined using the package' keyword at the
containing class, or when aclass is only needed within the context of its Java source file.
containing class. follows:
3 There are four types of inner classes in Java: 6 The syntax for defining a package is as
i. Non-static inner class :A non-static inner class, also known as an package com.example.mypackage;
inner class or a member class, is defined inside another class without com.example.mypackage is the name of the package.
the 'static' modifier. Non-static inner classes can access the members of In this example, using the
you need to import the package
their containing class, even if they are private. 7 To use a class froma package,
import' statement.
ii. Static nested class:A staticnested class is a class that is defined in eid is as tollows:
another class with the 'static' modifier. Static nested classes cx 8. The syntax for importing a package
import com.example.mypackage.MyClass;
instantiated without an instance of the containing class and can n
access the static members of their containing class. 'com.example.mypackage.MyClass'is the fully qualified
iii. Local inner class : Alocal inner class is a class that is defined In this example, that you want to import.
method or a block of code. Local inner classes can access the inside a name of the class
as java.lang', which
effectively final variables of the containing method or block final or predefined packages, suchand java.util', which
9 Java provides several of the Java language,
iv. Anonymous inner class : An anonymous inner class is a class that contains the core classes working with collections, dates, and other
is contains utility classes for
defined without a name and is used for implementing
extending classes. Anonymnous inner classes can only be interfaces data structures.
custom packages.
once and cannot be reused. instántiated 10. Java also allows
vou to ereate your own
a directory with the
package, you need to createfiles in that directory.
create a custom source
PART-3 4 To and place your Java
name of the package
CLASSPATH Setting for in Java.
Packages8 : Defining Package, CLASSPATH setting for packages
StaPPatic cImport
kages,
Import and Explain
Making JAR Files for Library Packages,
Networking, java.net
ue 2.18.
Naming Convention for Puckages,
Package.
2-18B(MCA-Sem-2) Inheritance, Interfaces and Packages
Object Oriented Programming 2-17B (MCA-Sem-2)
Que 2.20.
Write a short note on: import and staticimport.
Answer
1 In Java, the CLASSPATH is an environment variable that specifies the Answer
location of Java class files that the Java Virtual Machine (JVM) uses to Import :
run Java applications. A and
In Java, the import statement is used to bring classes, interfaces,
The CLASSPATH setting is used to tell the JVM where to look for other types into a Java source file, allowing you to use them without
2. 1
classes when they are referenced in code.
fully qualifying their names.
3 When a Java program is compiled, it is converted into bytecode, which is the java.util
For example, if you want to use the Scanner class from
2 follows :
package in your code, you can use the import statement as
stored in .class fles.
4. These files need to be located by the JVM when the program is executed. import java.util.Scanner;
5.
The CLASSPATH setting can be set using an operating system prefixing it with the
3. This allows you to use the Scanner' class without
environment variable or specified on the command line. full package name.
6 It can include directories, JAR files, and ZIP archives containing class
files. B. Static Import :
the import statement that
7 The static import statement is a variation of
For example, if you have aclass called MyClass' in a file called 1. class, such as static fields and
MyClass.class' located in the directory C:\java\classes', you can set the allows you to import static members of a
static methods.
CLASSPATH environment variable as follows on Windows :
constant from the java.lang. Math
set CLASSPATH=C:\java\classes 2. For example, ifyou want to use the PI import statemnent as follows:
can use the static
8. This willtell the JVM to look for classes in the 'C:\java\classes' directory. class in your code, you
import static java.lang. Math. PI;
directly without prefixing it with
Que 2.19. Explain how to make JAR files for library packages ? 3. This allows you touse the PI constant
the class name.
Answer
by naming convention for
1 In Java. a JAR(Java Archive) file is a file format used to bundle
multiple Que 2.21. What do you understand
Java class files and associated resources into a single file. packages ?
2. JAR files are commonly used to distribute libraries and frameworks
making it easy for developers to use and manage the code Answer
packages are guidelines for naming
3 To make a JAR file for a library package in Java, you can
follow these 1 In Java, naming conventions for understandable way.
Java packages in consistent
a and
general steps: helps make Java code more
Step 1: Create a directory for the JAR file and change to that 2 Following a standard naming convention helps avoid naming conflicts
and
directory.
Step 2: Compile the Javasource code into classfiles s using the javac readable, maintainable, and portable,
Step 3: Create a manifest file that specifies the main claass and any compiler. and errors. that package
for packages recommends domain
configuration options. The manifest file must be named other 3 The Java naming convention
lowercase and should be in reverse
name
placed in the META-INF directory. MANIFEST.MF
Step4 : Package the class files and the manifest file into a JAR file
and names should be all
order, separated by periods.
package name is unique and globally
jar' command. using the 4 This convention ensures that eachnaming conflicts between packages from
identifiable, and helps prevent
Step 5: Optionally, you can sign the JAR file usingtthe
to ensure the integrity and authenticity of the code. jarsigner command different organizations or developers.
organization's domain name is
'example.com' and
Once you have created the JAR file, you can
5 For example, if your library', the package name
4
developers who can then include it in their Java
distribute it to other you have a package for your library named
classes and resources it contains.
projects and use the should be com.example.library'.
Object Oriented Programming 2-19 B (MCA-Sem-2)
6 This naming convention makes it clear which organization the package
belongs to and avoids conflicts with other packages that might have the
same name.
Answer
1.
The java.net' package in Java provides a set of classes and interfaces for
networking programming, including support for TCP/TP sockets, UDP
sockets, and URL connections.
2. This package is widely used for developing networked applications in
Java.
3. Some of the key classes and interfaces in the java.net package include:
i. Socket:Represents a client-side TCP/IP socket connection to a
server. This class provides methods for opening and closing the
connection, reading and writing data, and setting socket options.
ii. ServerSocket: Represents aserver-side TCP/IP socket that listens
for incoming connections. This class provides methods for
new connections, reading accepting
and writing data, and setting socket
options.
iüi. Datagram Socket : Represents a socket for sending and receiving
UDP datagrams. This class provides methods for sending and
receiving datagrams, setting socket options, and joining multicast
groups.
iv. URL:Represents a Uniform
toa resource on the Internet orResourc Locator (URL) that points
a local network. This class provides
methods for opening connections to the resource and
from it. reading data
V.
URLConnection : Represents a connection to a URL
This class provides methods for reading and
resource, setting request properties, and writing resource.
data to
the
4.
handling authentication.
Using the classes and interfaces in the java.net'' package,
a wide range of networked applications, including web you can develop
peer-to-peer applications,and more. clients, servers,
For example, you can use the 'Socket' and
5.
ServerSocket'
implement a simple client-server application or the classes
'URLConnection' classes to access web resources over HTTp URL' andto
Object Oriented Programming SQ-8B MCA-Sem-2)
SQ-7B (MCA-Sem-2) 2 Marks Questions
2.6. What is interface 2
2 UNT
Inheritance, Interfaces
and Packges
(2 Marks Questions)
AnS In Java, an interface is a
or constants that a class contract that defines a set of methods and/
2.7. Describe the uses of
Ans. Following are sone of the
must implement.
interfaces in Jaya.
1. Defining contracts : main uses of interfaces in Java:
Interfaces can be used to define contracts
between different components of a Java program.
2. Encapsulating behavior : Interfaces can be used to
the behavior of a class. encapsulate
3. Enforcing standärds : Interfaces can be used to enforce
2.1. Discuss protected members in Java. programming standards across a project or
Ans. In Java,
protected access 4. Supporting multiple implementations :organization.
(variable or modifier is used to declare a member
method) of a class Iaterfaces can be
tosupport multiple impleméntations of a particular behavior. used
subclasses, and other classesthatin istheaccessible within the class, its
same package. Protected 5. Facilitating polymorphism : Interfaces ean be used to facilitate
members are less restrictive than
be accessed within the private nmembers, which can only polymorphism in Java programs.
class they are declared in.
2.2. 2.8. Distinguish between class and interface.
Ans.
Exemplify
In
the use of 'super
keyword. Ans.
object-oriented
refer to the immediateprogramming, the 'super' keyword is used to S.No. Feature Classes Interfaces
parent class of a subclass, also
superclass. It is commonly used in inheritance known as the 1 Definition Abiueprint for ereating Acontract for
methods and constructors from the
superclass. relationships to call objects implementing behavior.
2.3. What is class hierarchy in Java ? 2. Fields Can containinstance and Cannot containinstance or
Ans. In Java, aclass static felds static fields.
hierarchical tree hierarchy is a way
structure based of i
on their classes into a
Inheritance is a
class to inheritfeature object-oriented
of relationships. 2.9. Outline the use of 'extends' keywordin Java with syntax.
and methodsprogramming
a that allows
properties
class hierarchy in Java is from another class. The
Ans nJava, the extends keyword is used to ereate a subclass that
inherits the properties and behaviors of asuperclass. The syntax
Object class at typically
the root and other represented tree,
as a with the for using 'extends' is as follows :
classes in Java are classesbranching off from it. All
either direct or indirect class ChildClass extends ParentQlass
Object' class. descendants of the WChildClass body
2.4. Discuss about
Object'
Ans. In Java, the Object class isclass in Java.
2.10. What is extending interfaces in Java ?
other classes in Java extendthe root class of theclass
Objecthierarchy.
or inherit from the All Ahs: An interface can extend anbther interface, which means that the
directly or indirectly. This means class, either child interface inherits all the methods from the parent interface
that
instance the Object class, and can access
of every object in Java is an and can add additional methods of its own. This is known as
the Object class. the methods defined in extending interfaces.
2.5. Discuss. final' keyword in 2.11. What is object cloning ?
Ans. The 'final' keyword is a Java. Ans: Object cloning in Java is the process of creatinga duplicate of an
powerful tool for creating
enforcing immutability, and constants, existing object. In Java, object cloning can be performed using the
Java programs. preventing unexpected behavior in clone()' method, which is defined in the Object class.