MST 2
MST 2
Encapsulation
● Private fields: Class variables are made private so that they cannot be accessed
directly from outside the class.
● Public methods: Getter and setter methods are created to access and modify the value
of private variables indirectly.
● Controlled Access: The object has full control over the data members, preventing
unauthorized or harmful operations.
Example Code:
java
Copy code
class Employee {
// Private variables to achieve encapsulation
private String name;
private int age;
private double salary;
2. Inheritance
Inheritance allows one class (child/subclass) to inherit the fields and methods of another class
(parent/superclass). It helps in code reuse and establishing a relationship between classes.
● Super and Subclasses: The superclass is the parent class, and the subclass is the
child class that inherits properties and behaviors from the parent.
● Code Reusability: Inheritance helps to avoid redundancy by reusing the fields and
methods of the parent class.
● super Keyword: Used to refer to the immediate parent class constructor or method.
Example Code:
java
Copy code
// Parent class
class Animal {
String name;
// Constructor
public Animal(String name) {
this.name = name;
}
// Method to display information
public void makeSound() {
System.out.println(name + " is making a sound.");
}
}
3. Packages
Packages in Java are used to organize classes and interfaces in a logical manner. They help to
avoid class name conflicts, provide access control, and make it easier to maintain code.
● Built-in Packages: Java provides built-in packages (like java.util, java.io, etc.).
● User-defined Packages: You can create your own packages by using the package
keyword.
● Importing Packages: Classes from different packages can be imported using the
import statement.
Example Code:
java
Copy code
// Save this as Employee.java inside a folder named "mypackage"
package mypackage;
Command to compile:
bash
Copy code
javac -d . Employee.java
javac TestPackage.java
Run:
bash
Copy code
java TestPackage
4. Exception Handling
Exception handling in Java is the process of managing errors and exceptions that occur during
the execution of a program. Java uses try, catch, finally, throw, and throws to handle
exceptions.
Example Code:
java
Copy code
public class TestExceptionHandling {
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("Exception caught: " + e.getMessage());
} finally {
// This block will always execute
System.out.println("Finally block executed.");
}
Explanation of Example:
1. Division by zero: The try block contains a risky operation that throws an
ArithmeticException. It is caught by the catch block.
2. Finally block: Always executes regardless of the outcome.
3. Custom exception using throw: If the age is below 18, the custom exception is
thrown.
Output:
php
Copy code
Exception caught: / by zero
Finally block executed.
Exception caught: Age must be 18 or older.
Conclusion:
● Encapsulation ensures data security by using private fields and public methods.
● Inheritance allows code reusability by inheriting methods and fields from a parent class.
● Packages help organize code and avoid conflicts.
● Exception Handling ensures that runtime errors are managed gracefully, preventing
program crashes.
1. Explain the difference between class and interface. Explain how an
interface is used to achieve complete abstraction in Java.
● Class: A class in Java is a blueprint for creating objects and encapsulates methods and
variables. It can have concrete methods (with implementation) and abstract methods.
Classes support inheritance, allowing subclasses to inherit behavior from the parent
class.
● Interface: An interface is a collection of abstract methods (until Java 7). From Java 8
onward, interfaces can have default and static methods with implementations. Interfaces
are used to define a contract that classes must follow without providing implementation
for most methods (besides the default and static ones).
● Abstraction in Java: Complete abstraction is achieved in Java through interfaces
because they can have only abstract methods (before Java 8), ensuring that no method
has a body (except default/static). A class implementing an interface must provide the
implementation of all its abstract methods, thus enforcing the use of abstraction.
● Multiple Inheritance in Java: Java does not support multiple inheritance with classes to
avoid the "diamond problem" where ambiguity arises from multiple parent classes with
similar methods. However, multiple inheritance is supported through interfaces. A
class can implement multiple interfaces, inheriting their methods and thus achieving
multiple inheritance.
Example:
java
Copy code
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Method A from interface A");
}
● In this example, class C inherits methods from both A and B interfaces, implementing
multiple inheritance.
Program Example:
java
Copy code
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int data = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e);
} finally {
System.out.println("This block is always executed.");
}
}
}
Output:
csharp
Copy code
Caught an exception: java.lang.ArithmeticException: / by zero
This block is always executed.
4. A subclass can define its own methods and instance variables and it can
override the methods of a class it inherits. Give justification for this
statement with an example.
● Justification: In Java, a subclass inherits fields and methods from its superclass. It can
also define additional fields and methods specific to itself. Additionally, the subclass can
override the methods of its superclass, providing its own implementation of those
methods.
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
void run() {
System.out.println("Dog runs");
}
}
● In this example, the Dog class overrides the sound() method of the Animal class and
adds a new method run().
5. Explain the following with example: (a) Final method (b) this (c) Abstract
class (d) super
(a) Final method: A final method in Java cannot be overridden by subclasses. It is used to
prevent modification of critical methods.
Example:
java
Copy code
class A {
final void display() {
System.out.println("This is a final method");
}
}
class B extends A {
// This will cause an error
// void display() { System.out.println("Trying to override"); }
}
(b) this keyword: The this keyword refers to the current instance of the class. It can be used
to refer to instance variables and invoke the current class's methods or constructors.
Example:
java
Copy code
class Example {
int x;
Example(int x) {
this.x = x; // Refers to the instance variable
}
void display() {
System.out.println("Value of x: " + this.x);
}
}
(c) Abstract class: An abstract class in Java is a class that cannot be instantiated directly. It
can have both abstract methods (without implementation) and concrete methods (with
implementation). A subclass must provide implementations for all abstract methods.
Example:
java
Copy code
abstract class Animal {
abstract void sound();
void eat() {
System.out.println("Animal is eating");
}
}
(d) super keyword: The super keyword is used to refer to the immediate parent class object.
It can be used to call parent class methods and constructors.
Example:
java
Copy code
class A {
void display() {
System.out.println("Display method in class A");
}
}
class B extends A {
void display() {
super.display(); // Calls the method from class A
System.out.println("Display method in class B");
}
}
These answers provide a detailed explanation for each of the questions. If you need further
clarification or examples, feel free to ask!