[go: up one dir, main page]

0% found this document useful (0 votes)
5 views33 pages

B08 OOP Writeup2

Uploaded by

adhirajd673
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views33 pages

B08 OOP Writeup2

Uploaded by

adhirajd673
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Name: Abhishek Khodade.

Roll No: B-08


PRN No- 2324000416
Object Oriented Programming in java
Writeup 2

1)What is Interface in Java. Write Java Syntax for Interface. Write Java
Program example to declare and implement Interface in Class.
Definition: An interface in Java is a reference type, similar to a class, that
can contain only constants, method signatures, default methods, static
methods, and nested types. Interfaces cannot contain instance fields or
constructors. They are used to specify a set of methods that a class must
implement, promoting a form of abstraction and multiple inheritance.
Syntax of an Interface:
interface InterfaceName { //
abstract methods void
method1(); void method2(); //
default method default void
defaultMethod() { // method
body
}
// static method static
void staticMethod() { //
method body
}
}
Example Program:
// Defining the
interface interface
Animal { void eat();
void sleep();
}
// Implementing the interface in a
class class Dog implements Animal
{ public void eat() {
System.out.println("Dog is eating.");
}
public void sleep() {
System.out.println("Dog is sleeping.");
}
}

// Main class to test the


implementation public class Main
{ public static void main(String[] args)
{ Dog myDog = new Dog();
myDog.eat(); myDog.sleep();
}
}
Explanation:
• The Animal interface declares two abstract methods: eat() and sleep().
• The Dog class implements the Animal interface and provides concrete
implementations for the eat() and sleep() methods.
• In the Main class, an instance of Dog is created, and its methods are
invoked, resulting in the following output:
Dog is eating.
Dog is sleeping.
Diagram:
++
|| Animal <--- Interface
||
|
+ eat()
+ sleep()

^
|
|

|
Dog
|
+ eat()
+ sleep()

|
||
++

++
| <--- Implements Animal
||
|
||
++
1. What is relation between Interface and Class. Can single class
implement two Interface? If yes write Java Syntax to how single class
implements two Interfaces. Also write Java Program to show single class
implements two interface and add logic to all methods.
Relationship Between an Interface and a Class: In Java, an interface defines a
contract of abstract methods that a class can implement. While a class
represents a blueprint of objects with attributes and behaviors, an interface
specifies a set of methods that the class agrees to implement. This allows for a
separation of the "what" (interface) from the "how" (class implementation),
promoting flexibility and scalability in code design.
Implementing Multiple Interfaces: Yes, a single class in Java can implement
multiple interfaces. This is a way to achieve multiple inheritance, as Java
does not support multiple inheritance through classes.
Java Syntax for a Class Implementing Two Interfaces:
interface Interface1 {
void method1();
}

interface Interface2 {
void method2();
}
class MyClass implements Interface1, Interface2 {
public void method1() {
// Implementation of method1
}
public void method2() {
// Implementation of method2
}
}
Example Program:
// Defining the first interface
interface Animal {
void eat();
}
// Defining the second interface
interface Pet {
void play();
}
// Implementing both interfaces in a single class
class Dog implements Animal, Pet {
public void eat() {
System.out.println("Dog is eating.");
}
public void play() {
System.out.println("Dog is playing.");
}
}
// Main class to test the implementation
public class Main {
public static void main(String[] args)
{ Dog myDog = new Dog();
myDog.eat(); myDog.play();
}
}

Diagram:
Animal
++ + +
|| | Pet |
|
+ eat()
| | | |
| | + play() |
++ + +
^ ^
| || |+
+ +

|
++
| Dog |

||
|
+ eat() |
|| + play()
++

2. List Down One Real-Time Example Where: a. Java Class Uses a Single
Interface b. Java Class Uses Two Interfaces

a. Java Class Uses a Single Interface:


Real-Time Example: Consider a payment system where different payment
methods are implemented. Each payment method can be represented by
a class implementing a common interface.
Interface Definition:
interface Payment {
void processPayment(double amount);
}

Class Implementing the Interface:


class CreditCardPayment implements Payment {
public void processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
}
}
Explanation:
• The Payment interface defines a contract for processing payments.
• The CreditCardPayment class implements the Payment interface,
providing the specific logic for processing credit card payments.
Diagram:

+ +
| Payment | <--- Interface
| |
| + processPayment() |
+ +
^
|
|
+ +
| CreditCardPayment | <--- Implements Payment
| |
| + processPayment() |
+ +

b. Java Class Uses Two Interfaces:


Real-Time Example: Consider a scenario where a device can both print and
scan documents. The device can be represented by a class implementing
two interfaces: Printable and Scannable.
Interface Definitions:
interface Printable {
void printDocument(String document);
}

interface Scannable {
void scanDocument(String document);
}

Class Implementing Both Interfaces: class


MultiFunctionPrinter implements Printable, Scannable {
public void printDocument(String document) {
System.out.println

3. What is Inheritance in Object-Oriented Paradigm? Explain Various Types of


Inheritance with Diagram and Example.
Inheritance in Object-Oriented Paradigm: Inheritance is a fundamental
concept in object-oriented programming (OOP) that allows a new class,
known as a subclass or derived class, to acquire properties and behaviors
(fields and methods) from an existing class, referred to as a superclass or
base class. This mechanism promotes code reusability, modularity, and a
hierarchical classification of classes. In Java, inheritance is implemented using
the extends keyword.
Types of Inheritance:

1. Single Inheritance: A subclass inherits from a single superclass. This is


the most straightforward form of inheritance.

Diagram:
+ +
| Superclass |
+ +
|
v
+ +
| Subclass |
+ +

Example:
class Animal
{ void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal


{ void bark() {
System.out.println("The dog barks.");
}
}

2. Multilevel Inheritance: A chain of inheritance where a subclass inherits


from another subclass.
Diagram:
+ +
| Superclass |
+ +
|
v
+ +
| Subclass1 |
+ +
|
v
+ +
| Subclass2 |
+ +

Example:
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Mammal extends Animal {


void walk() {
System.out.println("This mammal walks.");
}
}

class Dog extends Mammal {


void bark() {
System.out.println("The dog barks.");
}
}

3. Hierarchical Inheritance: Multiple subclasses inherit from a single


superclass.
Diagram:
+ +
| Superclass |
+ +
/ \
/ \
v v
+ ++ +
| Subclass1 | | Subclass2 |
+ ++ +
Example:
class Animal
{ void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal


{ void bark() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


void meow() {
System.out.println("The cat meows.");
}
}
4. Multiple Inheritance: A subclass inherits from multiple
superclasses. Java does not support multiple inheritance with
classes to avoid ambiguity and complexity, but it can be achieved
using interfaces.
Diagram:
+ + + +
| Superclass1 | | Superclass2 |
+ + + +
\ /\
/v
v
+ +
| Subclass |
+ +

Example using Interfaces:


interface Canine
{ void bark();
}

interface Pet
{ void play();
}
class Dog implements Canine, Pet
{ public void bark() {
System.out.println("The dog barks.");
}

public void play() {


System.out.println("The dog plays.");
}
}

5. Hybrid Inheritance: A combination of two or more types of inheritance.


Java supports hybrid inheritance through interfaces.
Diagram:
+ +
| Superclass |
+ +
/ \
/ \
v v
+ ++ +
| Subclass1 | | Subclass2 |
+ ++ +
\ /\
/
v v
+ +
| Subclass3 |
+ +

Example using Interfaces:


interface Animal
{ void eat();
}
interface Mammal extends Animal
{ void walk();
}

class Dog implements Mammal


{ public void eat() {
System.out.println("The dog eats.");
}

public void walk() {


System.out.println("The dog walks.");
}
}

4. What are Superclass, Subclass, and Polymorphism Concepts in


Inheritance? Explain with the Help of Diagram and Java Syntax.
Superclass and Subclass:
• Superclass: The class from which properties and methods are inherited.
Also known as the parent or base class.
• Subclass: The class that inherits properties and methods from the
superclass. Also known as the child or derived class.
Diagram:
+ +
| Superclass |
+ +
^
|
+ +
| Subclass |
+ +

Java Syntax:
class Superclass {
// fields and methods
}

class Subclass extends Superclass {


// additional fields and methods
}

Polymorphism: Polymorphism allows objects to be treated as instances of


their superclass rather than their actual class. This enables a single interface to
represent different underlying forms (data types). class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


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

class Cat extends Animal {


void makeSound() {
System.out.println("Cat meows");
}
}

public class TestPolymorphism {


public static void main(String[] args) {
Animal a; // Reference of superclass

a = new Dog(); // Upcasting


a.makeSound(); // Calls Dog's makeSound()

a = new Cat(); // Upcasting


a.makeSound(); // Calls Cat's makeSound()
}
}

5. Mini Project Idea: Library Management System


Project Overview: The Library Management System (LMS) is designed to
manage the operations of a library, including tracking books, users, and
transactions. This system ensures efficient handling of book inventories,
user registrations, borrowing, and returning processes.UpGrad Classes,
Attributes, and Methods:

1. Class: Book o

Attributes:
▪ bookID: Unique identifier for each book.
▪ title: Title of the book.
▪ author: Author of the book.
▪ publisher: Publisher of the book.
▪ isAvailable: Boolean indicating the availability status. o

Methods:
▪ getDetails(): Returns the details of the book.
▪ checkAvailability(): Checks if the book is available for
borrowing.

2. Class: User o

Attributes:
▪ userID: Unique identifier for each user.
▪ name: Name of the user.
▪ email: Email address of the user.
▪ phone: Contact number of the user. o Methods:
▪ register(): Registers a new user.
▪ updateProfile(): Updates user profile information.

3. Class: Member
(inherits from
User)
o Attributes:

▪ membershipID: Unique membership identifier.


▪ borrowedBooks: List of books currently borrowed. o

Methods:
▪ borrowBook(Book book): Allows a member to borrow a
book.
▪ returnBook(Book book): Allows a member to return a
borrowed book.
4. Class: Librarian (inherits from User)
o Attributes:

▪ employeeID: Unique employee identifier.


o Methods:

▪ addBook(Book book): Adds a new book to the inventory.


▪ removeBook(Book book): Removes a book from the
inventory.
▪ manageUsers(): Manages user registrations and profiles.

5. Class: Transaction o Attributes:


▪ transactionID: Unique identifier for each transaction.
▪ book: The book involved in the transaction.
▪ member: The member involved in the transaction.
▪ issueDate: Date when the book was issued.
▪ dueDate: Date when the book is due for return.
▪ returnDate: Date when the book was returned.
o Methods:

▪ createTransaction(): Records a new borrowing transaction.


▪ closeTransaction(): Closes a transaction upon book return.
Inheritance Implementation: In this design, the Member and Librarian classes
inherit from the User class, promoting code reusability and a clear hierarchical
structure. Common attributes like userID, name, email, and phone are defined
in the User class and inherited by both Member and Librarian classes.

6. Java Application Design for Specific Domains

a. Education Domain
The Education Management System consists of multiple entities like teachers,
students, administrative staff, and accounts. Using inheritance and
interfaces, we can design a structured and scalable system.

Classes, Attributes, and Methods:

1. Superclass: Person (Base Class)


• Attributes:
o personID: Unique identifier.
o name: Full name. o address: Residential address.
o phone: Contact number.
• Methods: o getDetails(): Returns personal details.
2. Subclass: Teacher (Inherits from Person)
• Attributes:
o employeeID: Unique employee identifier.
o subjects: List of subjects taught.
• Methods: o assignGrades(Student student): Assigns grades
to a student. o prepareLesson(): Prepares lesson plans.

3. Subclass: Student (Inherits from Person)


• Attributes:
o studentID: Unique student identifier.
o courses: List of enrolled courses.
• Methods: o enrollCourse(Course course): Enrolls in a new
course.
o viewGrades(): Views grades for courses.

4. Subclass: AdministrativeStaff (Inherits from Person)


• Attributes:
o staffID: Unique staff identifier.
o department: Department of work.
• Methods:
o manageRecords(): Manages institutional records.

5. Independent Class: AccountDepartment


• Attributes:
o budget: Total budget allocated.
o expenses: List of expenses.
• Methods: o processSalary(Teacher teacher): Processes
salary for teachers.
o manageBudget(): Manages the department's budget.

Interfaces and Inheritance:


To enforce common behavior across different roles, we can use interfaces.
Interface: Evaluatable
• Methods:
o evaluateStudent(Student student): Evaluates a
student's performance.
Interface: Manageable
• Methods:
o manageRecords(): Manages records of students,
teachers, and staff. o generateReports(): Generates
reports related to education.

Diagram Representation of the Education System


Person

| | |
Teacher Student AdministrativeStaff
| |
| AccountDepartment
|
Evaluatable (Interface)
Code Representation in Java
// Superclass
class Person {
String personID, name, address, phone;

void getDetails() {
System.out.println("Name: " + name + ", Address: " + address);
}
}

// Interface for Evaluation


interface Evaluatable {
void evaluateStudent(Student student);
}

// Subclass: Teacher
class Teacher extends Person implements Evaluatable {
String employeeID;
String subjects;

public void evaluateStudent(Student student) {


System.out.println("Evaluating student: " + student.name);
}

void assignGrades(Student student) {


System.out.println("Grades assigned to: " + student.name);
}
void prepareLesson() {
System.out.println("Lesson prepared.");
}
}

// Subclass: Student class


Student extends Person {
String studentID;
String courses;

void enrollCourse(String course) {


System.out.println("Enrolled in: " + course);
}

void viewGrades() {
System.out.println("Viewing grades...");
}
}

// Subclass: AdministrativeStaff class


AdministrativeStaff extends Person {
String staffID, department;

void manageRecords() {
System.out.println("Managing records...");
}
}
// Independent Class: AccountDepartment
class AccountDepartment {

double budget;

void processSalary(Teacher teacher) {


System.out.println("Salary processed for: " + teacher.name);
}

void manageBudget() {
System.out.println("Managing budget...");
}
}

// Main Class
public class EducationSystem { public
static void main(String[] args)
{ Teacher t1 = new Teacher();
t1.name = "John Doe"; Student s1 =
new Student(); s1.name = "Alice";

t1.evaluateStudent(s1);
t1.assignGrades(s1);
}
}

7. What is a Java Package? What is the Use of Java Packages? What Directory
Structure is Followed When We Create a Package? What Naming
Conventions are Used When We Write Java Packages?
Java Package: A package in Java is a namespace that organizes a set of
related classes and interfaces. Think of it as a folder in a file directory that
contains related files. Packages help in grouping related classes, preventing
naming conflicts, and controlling access.
Uses of Java Packages:

1. Organization: Packages organize classes and interfaces into a structured


hierarchy, making the codebase more manageable.

2. Avoiding Naming Conflicts: By grouping classes into packages, classes


with the same name can exist in different packages without conflict.

3. Access Control: Packages provide access protection; classes within the


same package can access each other's package-private members.

4. Reusability: Packages allow developers to reuse classes and interfaces


across different projects.
Directory Structure When Creating a Package: The directory structure of a
Java package corresponds to its namespace. For example, a package named
com.example.project would have the following directory structure:

com/
└── example/
└── project/

Each dot (.) in the package name represents a new directory level.
Naming Conventions for Java Packages:
• Lowercase Letters: Package names are written in all lowercase letters
to avoid conflicts with class or interface names. cite turn0search0
• Reverse Domain Name: Organizations often use their reversed
Internet domain name to begin their package names. For example, a
company with the domain example.com would use com.example as
the base package name. cite turn0search0
• Concatenation Without Underscores: When a package name is
composed of multiple words, they are concatenated without
underscores. For instance, formvalidator instead of form_validator.
cite turn0search2
8. What is a Built-in Package in Java? Explain with Names of Packages.
Built-in Packages in Java: Built-in packages are predefined packages provided
by the Java Development Kit (JDK). They contain a vast collection of classes
and interfaces that facilitate various programming tasks, such as data
structures, networking, and input/output operations.
Examples of Built-in Packages:

1. java.lang: Contains fundamental classes like String, Math, Integer, and


System. This package is automatically imported into every Java program.

2. java.util: Provides utility classes such as collections framework (List, Set,


Map), date and time facilities, and random number generation.

3. java.io: Includes classes for input and output operations, like File,
InputStream, OutputStream, Reader, and Writer.

4. java.net: Offers classes for networking applications, including Socket,


ServerSocket, and URL.

5. java.awt: Contains classes for creating user interfaces and for painting
graphics and images.

6. javax.swing: Provides a set of 'lightweight' (all-Java language)


components that, to the maximum degree possible, work the same on
all platforms.

7. java.sql: Offers classes and interfaces for accessing and processing data
stored in a data source using the Java programming language.
These built-in packages simplify development by providing ready-to-use
classes and interfaces for common tasks.

9. What is a User-defined Package in Java? Explain with Example. Which


Commands Will You Use to Create a User-defined Package?
User-defined Package: A user-defined package is a package created by
developers to group their own classes and interfaces. This helps in
organizing code, avoiding naming conflicts, and enhancing modularity.
Example:
Creating a Package:Define the package at the beginning of your Java source
file using the package keyword.
package com.example.utilities;
public class Utility {
public void displayMessage() {
System.out.println("Hello from the Utility class!");
}
}

Compiling the Package:


Navigate to the source directory and compile the Java file. The
directory structure should match the package name.
javac com/example/utilities/Utility.java

Using the Package in Another Class:


Import the user-defined package using the import statement.
import com.example.utilities.Utility;

public class Test { public static void


main(String[] args) { Utility util =
new Utility(); util.displayMessage();
}
}

Compiling and Running the Program:


javac Test.java
java Test

Commands to Create a User-defined Package:


Define the Package:
Use the package keyword at the top of your Java source file.
package com.example.mypackage;

Set Up Directory Structure:


Create directories that match your package name. For
com.example.mypackage, the structure would be:
mkdir -p com/example/mypackage
Save and Compile:
Save your Java file in the appropriate directory and compile it.
javac com/example/mypackage/MyClass

10. What is a User-Defined Package in Java? Explain with an Example. Which


Commands Will You Use to Create a User-Defined Package?
What is a User-Defined Package?
A user-defined package in Java is a package created by a programmer to
organize and group related classes, interfaces, and sub-packages. It helps in
maintaining a clean project structure, avoiding naming conflicts, and
improving reusability.
In Java, we use the package keyword to create a user-defined package.

Steps to Create a User-Defined Package

1. Create a Package: o Use the package keyword at the beginning of the


Java file.

2. Compile the File:


o Use javac -d . ClassName.java to store the compiled file in the
correct package directory.

3. Use the Package in Another Class:


o Use import to access the classes from the package.
Example of a User-Defined Package
Step 1: Create a Package (File: MyPackageClass.java)
// Define package
package mypackage;

public class MyPackageClass


{ public void displayMessage() {
System.out.println("Hello from MyPackageClass!");
}
}
• This file should be saved inside a folder named mypackage.
Step 2: Compile the Java File
Run the following command in the terminal or command prompt:
javac -d . MyPackageClass.java
This will create a folder named mypackage in the current directory, and
the .class file will be stored inside it.
Step 3: Use the Package in Another Class (File: TestPackage.java)
// Import the user-defined package import
mypackage.MyPackageClass;

public class TestPackage {


public static void main(String[] args) {
MyPackageClass obj = new MyPackageClass();
obj.displayMessage(); // Accessing method from the package
}
}
Step 4: Compile and Run the Program
• Compile the TestPackage.java file:
• javac TestPackage.java
• Run the program:
• java TestPackage Output:
Hello from MyPackageClass!

Commands to Create and Use a User-Defined Package

Step Command
Create and compile a package javac -d . MyPackageClass.java
Compile the class using the package javac TestPackage.java
Run the program java TestPackage

Advantages of User-Defined Packages in Java

1. Code Organization – Helps in grouping related classes together.

2. Encapsulation – Provides access control and security.


3. Avoids Naming Conflicts – Prevents duplicate class names across
projects.

4. Reusability – Once created, packages can be reused in different


applications.
By using user-defined packages, Java applications become modular, scalable,
and well-structured.

11. Proposed Package Structure for the Library Management System Mini
Project
Designing an organized package structure is crucial for the maintainability
and scalability of a Java project. For the Library Management System (LMS)
mini project, a feature-based package organization is recommended, as it
groups related classes by functionality, enhancing modularity and
readability.
Proposed Package Structure:

1. com.librarymanagement o
**model**
▪ Contains classes representing the core entities of the
system.
▪ Classes:
▪ Book
▪ User
▪ Member
▪ Librarian
▪ Transaction
o **service**

▪ Contains classes that implement the business logic and


operations.
▪ Classes:
▪ BookService
▪ UserService ▪ TransactionService
o dao (Data Access Object)
▪ Manages data persistence and retrieval from the
database.
▪ Classes:
▪ BookDAO
▪ UserDAO
▪ TransactionDAO
o **ui**
▪ Handles the user interface components of the
application.
▪ Classes:
▪ MainMenu
▪ BookUI
▪ UserUI
▪ TransactionUI
o **util**
▪ Contains utility classes and helper
functions.
▪ Classes:
▪ DatabaseConnection
▪ DateUtil Explanation of Packages:
• model Package:
o Defines the data structures and entities used within the LMS.
o Example: The Book class would include attributes like bookID,
title, author, and methods such as getDetails() and
checkAvailability().
• service Package:
o Implements the core functionalities and business logic.
o Example: The BookService class might include methods like
addBook(), removeBook(), and searchBooks().
• dao Package:
o Manages interactions with the database, ensuring data is
correctly stored and retrieved.
o Example: The BookDAO class would handle SQL operations
related to the Book entity.
• ui Package:
o Manages the user interface, facilitating user interactions with the
system.
o Example: The MainMenu class could present options like "Add
Book", "Issue Book", and "Return Book" to the user.
• util Package:
o Provides utility functions and common tools used across the
application.
o Example: The DatabaseConnection class would manage the
connection to the database, while DateUtil might offer date
formatting utilities.

You might also like