IA2 scheme
IA2 scheme
Kumbalgodu, Bangalore-74
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Scheme & Solution
INTERNALS ASSESSMENT-II
Subject : Object Oriented Programming using Java
Subject Code : BCS306A
Semester& Section : 3rd Sem
1.a. How do you pass arguments to superclass constructor through the subclass constructor? Explain with a code snippet. (10)
To pass arguments to a superclass constructor through a subclass constructor, you use the super() function in the subclass constructor. This
calls the constructor of the superclass with the provided arguments, allowing you to initialize both the superclass and subclass with the
necessary values.
Example program:
python
Copy code
class Animal:
self.name = name
class Dog(Animal):
# Call the superclass (Animal) constructor and pass the 'name' argument
super().__init__(name)
self.breed = breed
# Usage
Explanation
1. The Animal class has an __init__ method that initializes the name attribute.
2. The Dog class, a subclass of Animal, has its own __init__ method with parameters for name and breed.
3. Inside the Dog constructor, super().__init__(name) calls the __init__ method of Animal, passing the name argument to initialize
the name attribute in Animal.
This way, the subclass constructor can pass parameters to the superclass constructor while also initializing any subclass-specific attributes.
1.b. Explain the following keywords. i)this ii) super iii) final iv) static (10)
1. this
Example:
java
Copy code
this.name = name; // 'this.name' refers to the instance variable, 'name' refers to the parameter
Note: Helps in disambiguating class fields and parameters with the same name.
2. super
Usage: Used to call superclass methods, constructors, or to access superclass fields from a subclass.
Example:
public Animal() {
System.out.println("Animal created");
public Dog() {
System.out.println("Dog created");
Note: The super() call must be the first statement in a subclass constructor if you want to call the superclass constructor explicitly.
3. final
Usage:
Example:
java
Copy code
public final class MathConstants {
System.out.println("Drawing shape");
Note: A final variable must be initialized only once, either at the time of declaration or in the constructor.
4. static
Purpose: Indicates that a variable, method, or nested class belongs to the class itself rather than to instances of the class.
Usage:
o Static Nested Classes: A nested class that does not require an instance of the outer class.
o
Example:
java
Copy code
public Counter() {
System.out.println("Total count: " + count); // Static method can access static variables
Note: Static methods cannot access instance (non-static) variables or methods directly.
2.a. What do you mean by method overriding? Discuss with a programming example (10)
Method Overriding is a feature in object-oriented programming where a subclass provides a specific implementation of a method that is
already defined in its superclass. This allows the subclass to define a behavior that’s specific to its type, even though the method is called
through a superclass reference.
1. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.
2. It is used to achieve runtime polymorphism.
3. The @Override annotation is often used before an overridden method to make it clear and help catch errors if the method signatures
don’t match.
java
Copy code
// Superclass
class Animal {
// Subclass
@Override
System.out.println("Dog barks");
myAnimal.sound(); // Calls Animal's sound() method: Output -> "Animal makes a sound"
myDog.sound(); // Calls Dog's overridden sound() method: Output -> "Dog barks"
Explanation
1. Superclass (Animal): The Animal class has a sound() method that simply prints "Animal makes a sound".
2. Subclass (Dog): The Dog class extends Animal and overrides the sound() method to print "Dog barks".
3. Runtime Behavior: When we create an Animal reference pointing to a Dog object (Animal myDog = new Dog();), the overridden
sound() method in Dog is called, not the one in Animal.
Dynamic Method Dispatch: Allows the program to decide at runtime which method to execute, enabling polymorphism.
Custom Behavior in Subclass: Provides specific implementation for subclass types while using the same method signature,
enhancing flexibility and reusability.
2.b. Explain Dynamic Method Dispatch with suitable programming example. (10)
Dynamic Method Dispatch (also known as runtime polymorphism) is a process in which a call to an overridden method is resolved at runtime
rather than at compile time. It occurs when a superclass reference variable holds a subclass object, and the method that gets called is determined
based on the actual object type, not the reference type.
Dynamic method dispatch enables Java to implement runtime polymorphism, allowing methods in subclass objects to be accessed through
superclass references.
When a method is called on a superclass reference holding a subclass object, Java looks at the actual object type to determine which method
to invoke. This enables the program to select the appropriate method implementation at runtime.
Consider the following example to understand how dynamic method dispatch works:
java
Copy code
// Superclass
class Animal {
// Subclass Dog
@Override
System.out.println("Dog barks");
// Subclass Cat
@Override
System.out.println("Cat meows");
Explanation
1. Superclass (Animal): The Animal class has a sound() method that will be overridden in each subclass.
2. Subclass (Dog): The Dog class overrides the sound() method to print "Dog barks".
3. Subclass (Cat): The Cat class overrides the sound() method to print "Cat meows".
o Assigning myAnimal to a Dog object calls the Dog’s version of sound(), outputting "Dog barks".
o Reassigning myAnimal to a Cat object then calls the Cat’s version of sound(), outputting "Cat meows".
Runtime Polymorphism: Enables polymorphic behavior, where the actual method that gets executed is based on the runtime
object type, not the reference type.
Flexibility and Extensibility: Allows programs to decide at runtime which specific implementation to invoke, making the program
more flexible and extensible.
Dynamic method dispatch is fundamental to achieving polymorphism, one of the key principles of object-oriented programming, enabling
more flexible and reusable code.
3.a. Create an abstract class called Employee. Include the members: Name, EmpID and an abstract method cal_sal(). Create two
inherited classes SoftwareEng (with the members basic and DA) and HardwareEng (with members basic and TA). Implement runtime
polymorphism (dynamic method dispatch) to display salary of different employees by creating array of references to superclass. (10)
String name;
int empID;
this.name = name;
this.empID = empID;
}
// Abstract method to calculate salary
double basic;
super(name, empID);
this.basic = basic;
this.DA = DA;
@Override
double basic;
super(name, empID);
this.basic = basic;
this.TA = TA;
@Override
System.out.println("----------------------");
Output:
Salary: 65000.0
----------------------
Salary: 50000.0
----------------------
Salary: 75000.0
3.b. Design Interface called polygon with a method called area (). Implement this Interface to create different classes like Square,
Rectangle and print the area of Square and Rectangle. (10)
// Interface Polygon
interface Polygon {
double area();
double side;
this.side = side;
@Override
double length;
double width;
this.length = length;
this.width = width;
@Override
}
// Main class to test the implementation
Polygon rectangle = new Rectangle(4, 6); // 4 and 6 are the length and width of the rectangle
4.a. What do you mean by a package? How to find Packages and CLASSPATH? How do you import in a Java program? Explain with
a program. (10)
In Java, a package is a way of grouping related classes and interfaces together, much like folders on a computer, making the code modular
and easier to maintain. Packages help avoid naming conflicts by providing namespaces and allow for more organized project structures.
1. Finding Packages:
o Java provides several built-in packages like java.util, java.io, and java.lang.
o To list available packages, you can browse the jre/lib and lib folders in your Java installation, which contain core
libraries.
2. CLASSPATH:
o CLASSPATH is an environment variable that tells the Java compiler and Java runtime where to find the classes and
packages.
View: Run echo %CLASSPATH% on Windows or echo $CLASSPATH on macOS/Linux in the command
line.
Set CLASSPATH:
o To use a class from another package, you use the import keyword.
o You can either import a single class (import packageName.ClassName;) or an entire package (import packageName.*;).
Let's create a simple program that defines a custom package myPackage with a Calculator class and then uses it in the main program.
Save this code in a file named Calculator.java inside a folder called myPackage:
java
Copy code
// Calculator.java in myPackage
package myPackage;
return a + b;
return a - b;
bash
Copy code
javac myPackage/Calculator.java
Now, let’s create a program that imports and uses the Calculator class from myPackage.
java
Copy code
// Print results
Ensure CLASSPATH is set to the parent directory of myPackage or include it directly while running:
1. Compile:
bash
Copy code
javac Main.java
2. Run:
bash
Copy code
java Main
Explanation
2. Import Statement (import myPackage.Calculator;): Allows Main.java to access Calculator without needing the full path.
3. Using Calculator Methods: The Main class creates an instance of Calculator and calls its add and subtract methods.
This example demonstrates how to create a package, import it into another class, and use its functionality in Java.
4.b. Define an interface. Explain how to define and implement an interface with an example. (10)
An interface in Java is a reference type that can contain only constants, method signatures, default methods, static methods, and nested types.
Interfaces are abstract by nature, meaning they provide a contract for classes to implement but do not provide any concrete behavior
themselves.
1. Defines Methods Without Implementations: Methods in an interface are abstract by default (no body).
2. Implements Multiple Inheritance: A class can implement multiple interfaces, allowing Java to achieve multiple inheritance.
3. Access Modifiers: All methods in an interface are implicitly public and abstract, and fields are implicitly public, static, and final.
4. Default and Static Methods: Java 8 and later allow default and static methods in interfaces, which can have a body.
Defining an Interface
java
Copy code
interface InterfaceName {
// Constant declarations
void myMethod();
Implementing an Interface
A class implements an interface using the implements keyword and must provide implementations for all of its abstract methods. If a class
fails to implement all methods, it must be declared abstract.
In this example, we’ll define an interface called Shape with an abstract method area() and then implement it in Circle and Rectangle classes.
java
Copy code
interface Shape {
double area();
java
Copy code
// Constructor
this.radius = radius;
@Override
Copy code
// Constructor
this.length = length;
this.width = width;
@Override
Here’s the Main class demonstrating the use of the Shape interface:
java
Copy code
Explanation
1. Interface (Shape): Declares an abstract method area() that classes implementing this interface must define.
3. Interface References:
o In the Main class, Shape interface references (circle and rectangle) hold instances of Circle and Rectangle, respectively.
Polymorphism: Interface references enable polymorphic behavior by allowing different class implementations to be treated
uniformly.
5.a. Explain the access protection for packages in Java with programming examples (10)
In Java, access protection within packages is governed by access modifiers: public, protected, default (no modifier), and private. These access
levels determine the visibility of classes, methods, and fields across different packages and classes.
2. protected: Accessible within the same package and by subclasses in other packages.
3. default (package-private): Accessible only within the same package. If no access modifier is specified, it’s considered default.
Let’s look at a scenario with two packages to see how access protection works in Java.
In the Parent class, we’ll define fields and methods with different access modifiers.
java
Copy code
// packageA/Parent.java
package packageA;
System.out.println("Public Method");
System.out.println("Protected Method");
}
void defaultMethod() {
System.out.println("Default Method");
System.out.println("Private Method");
System.out.println(publicField);
System.out.println(protectedField);
System.out.println(defaultField);
System.out.println(privateField);
publicMethod();
protectedMethod();
defaultMethod();
privateMethod();
In this package, we’ll create a Child class that extends Parent to demonstrate which members are accessible through inheritance.
java
Copy code
// packageB/Child.java
package packageB;
import packageA.Parent;
System.out.println(publicField); // Accessible
publicMethod(); // Accessible
java
Copy code
// packageB/Test.java
package packageB;
import packageA.Parent;
System.out.println(parent.publicField); // Accessible
parent.publicMethod(); // Accessible
o publicField and publicMethod() in Parent are accessible everywhere, including Child and Test classes in packageB.
2. protected Access:
o protectedField and protectedMethod() are accessible in Child class because Child inherits from Parent. However, they
are not accessible in Test class, which does not inherit from Parent.
o defaultField and defaultMethod() are accessible only within the packageA package. They are not accessible in Child
(since it’s in packageB) or in the Test class.
4. private Access:
o privateField and privateMethod() are only accessible within the Parent class itself and are not accessible in either Child
or Test classes.
Output
plaintext
Copy code
Public Field
Public Method
Public Field
Protected Field
Public Method
Protected Method
Access Modifier Same Class Same Package (Non-Subclass) Subclass (Same Package) Subclass (Different Package) Other Packages
public ✔ ✔ ✔ ✔ ✔
default ✔ ✔ ✔ ✘ ✘
private ✔ ✘ ✘ ✘ ✘
This example illustrates how access modifiers control the visibility of fields and methods in Java across classes and packages, ensuring
encapsulation and controlled access within projects.
5.b. Discuss the following with Java code snippet. i) Returning Objects ii) Recursion (10)
i) Returning Objects
In Java, methods can return objects. This can be useful for methods that need to return instances of classes. When a method returns an object,
it can return a new instance, an existing object, or an object passed into the method.
In this example, we’ll create a Book class with a method that returns a Book object.
java
Copy code
class Book {
this.title = title;
this.author = author;
myBook.displayInfo();
Explanation
1. Book Class: Defines a constructor and a static method createBook() that returns a new Book object.
3. Using Returned Object: In the Main class, we call createBook to get a Book object and then call displayInfo to print the details.
ii) Recursion
Recursion is a technique in which a method calls itself to solve a problem. A recursive method typically has a base case (to stop recursion)
and a recursive case (where the method calls itself).
java
Copy code
class FactorialCalculator {
return 1;
int number = 5;
Explanation
o The base case checks if n is less than or equal to 1. If true, it returns 1, stopping further recursion.
o The recursive case calculates n * factorial(n - 1), which calls factorial again with a smaller argument.
2. Using Recursion:
plaintext
Copy code
These examples illustrate returning objects and using recursion in Java. Returning objects is a powerful feature for encapsulation and reuse,
while recursion is useful for problems that can be broken down into smaller, self-similar subproblems.