0% found this document useful (0 votes)
39 views14 pages

MST 2

Uploaded by

gurly101
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)
39 views14 pages

MST 2

Uploaded by

gurly101
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/ 14

1.

Encapsulation

Encapsulation is one of the core concepts of Object-Oriented Programming (OOP) in Java. It is


the mechanism of restricting direct access to some of the object’s properties and methods and
protecting the object’s integrity by bundling the data (variables) and methods that operate on the
data into a single unit, typically a class. This is often achieved by making the data members of a
class private and providing public getter and setter methods to access and update these
fields.

Key Points of 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;

// Constructor to initialize the values


public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}

// Getter method for name


public String getName() {
return name;
}

// Setter method for name


public void setName(String name) {
this.name = name;
}

// Getter method for age


public int getAge() {
return age;
}

// Setter method for age


public void setAge(int age) {
if (age > 0) { // Age validation
this.age = age;
} else {
System.out.println("Invalid age.");
}
}

// Getter method for salary


public double getSalary() {
return salary;
}

// Setter method for salary


public void setSalary(double salary) {
if (salary > 0) {
this.salary = salary;
} else {
System.out.println("Invalid salary.");
}
}
}

public class TestEncapsulation {


public static void main(String[] args) {
// Creating an employee object
Employee emp = new Employee("Alice", 25, 50000);
// Accessing and modifying private fields via public methods
System.out.println("Name: " + emp.getName());
System.out.println("Age: " + emp.getAge());
System.out.println("Salary: " + emp.getSalary());

// Modifying the values using setter methods


emp.setName("Bob");
emp.setAge(30);
emp.setSalary(60000);

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


System.out.println("Updated Age: " + emp.getAge());
System.out.println("Updated Salary: " + emp.getSalary());
}
}

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.

Key Points of Inheritance:

● 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.");
}
}

// Child class inheriting from Animal


class Dog extends Animal {
String breed;

// Constructor for Dog class


public Dog(String name, String breed) {
super(name); // Call the parent class constructor
this.breed = breed;
}

// Method specific to Dog class


public void displayInfo() {
System.out.println("Name: " + name + ", Breed: " + breed);
}

// Overriding makeSound method


@Override
public void makeSound() {
System.out.println(name + " is barking.");
}
}

public class TestInheritance {


public static void main(String[] args) {
// Create a Dog object
Dog dog = new Dog("Buddy", "Golden Retriever");

// Access parent class methods and child class methods


dog.displayInfo(); // Inherited behavior
dog.makeSound(); // Overridden behavior
}
}

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.

Key Points of Packages:

● 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:

Create a package named mypackage

java
Copy code
// Save this as Employee.java inside a folder named "mypackage"
package mypackage;

public class Employee {


private String name;
private int id;

public Employee(String name, int id) {


this.name = name;
this.id = id;
}

public void display() {


System.out.println("Employee Name: " + name + ", ID: " + id);
}
}

Using the package in another class


java
Copy code
// Save this as TestPackage.java
import mypackage.Employee;

public class TestPackage {


public static void main(String[] args) {
// Create an Employee object from the mypackage package
Employee emp = new Employee("John", 101);
emp.display();
}
}

● You need to compile Employee.java and TestPackage.java using the package


system.

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.

Key Points of Exception Handling:

● Checked Exceptions: Must be handled using try-catch or declared using throws.


● Unchecked Exceptions: Do not need to be declared or handled explicitly (like
NullPointerException).
● Try-catch block: Used to wrap code that may throw exceptions and handle them
appropriately.
● Finally block: Always executed, regardless of whether an exception was thrown or not.

Example Code:
java
Copy code
public class TestExceptionHandling {

public static void main(String[] args) {


try {
// Risky code that may throw an exception
int num1 = 10;
int num2 = 0;

// This will throw an ArithmeticException (division by


zero)
int result = num1 / num2;
System.out.println("Result: " + result);

} 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.");
}

// Example of throw keyword


try {
validateAge(15);
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}

// Method that throws a custom exception


public static void validateAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}
}

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.

2. Explain how multiple inheritance can be implemented in Java. Justify


your statement with an example.

● 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");
}

public void methodB() {


System.out.println("Method B from interface B");
}
}

public class TestMultipleInheritance {


public static void main(String[] args) {
C obj = new C();
obj.methodA();
obj.methodB();
}
}

● In this example, class C inherits methods from both A and B interfaces, implementing
multiple inheritance.

3. Explain how Java handles exceptions. Write a program that


demonstrates the use of try, catch, and finally keywords.

● Exception Handling in Java: Java handles exceptions using the


try-catch-finally block. The code that might throw an exception is enclosed in the
try block, and the catch block catches and handles the exception. The finally block
contains code that will always execute, regardless of whether an exception is thrown or
not. Exceptions in Java are objects that extend from the Throwable class.

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");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}

void run() {
System.out.println("Dog runs");
}
}

public class TestInheritance {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Calls the overridden method
dog.run(); // Calls the method defined in Dog class
}
}

● 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");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

(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");
}
}

public class TestSuper {


public static void main(String[] args) {
B obj = new B();
obj.display();
}
}

These answers provide a detailed explanation for each of the questions. If you need further
clarification or examples, feel free to ask!

You might also like