KEMBAR78
Unit 2 Answers | PDF | Method (Computer Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
11 views27 pages

Unit 2 Answers

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)
11 views27 pages

Unit 2 Answers

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/ 27

Unit II Question Bank Answers

1.Explain the fundamentals of a class in Java with an example, and demonstrate how objects are
declared, object reference variables are assigned, and analyse the importance of object reference
variables in program execution.
Ans:
Fundamentals of a class in Java
➢ Perhaps the most important thing to understand about a class is that it defines a new data type.
➢ Once defined, this new type can be used to create objects of that type.
➢ Thus, a class is a template for an object, and an object is an instance of a class.
Declaring Objects

➢ When you create a class, you are creating a new data type. You can

use this type to declare objects of that type.

➢ However, obtaining objects of a class is a two-step process.

➢ First, you must declare a variable of the class type. This variable

does not define an object.

➢ Instead, it is simply a variable that can refer to an object. Second,

you must acquire an actual, physical copy of the object and assign
it to that variable.

➢ You can do this using the new operator. The new operator

dynamically allocates (that is, allocates at run time) memory for an


object and returns a reference to it.

➢ This reference is, more or less, the address in memory of the object

allocated by new. This reference is then stored in the variable.


Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Assigning objects to reference variables
Box b1 = new Box();
Box b2 = b1;
Both b1 and b2 refer to the same object.

No new object is created; b2 just points to the same one as b1.

Changes made through b2 also affect the object b1 refers to.

They are not permanently linked — changing one won’t affect the other’s reference.

b1 = null;
Now b1 points to nothing, but b2 still refers to the object.
Importance of obeject reference variable in program execution

Feature Why It Matters


Access You use references to interact with objects
Efficiency Prevents copying large objects
Shared Access Lets multiple parts of a program share and modify the same object
Memory Management Helps Java track which objects are no longer needed

2. Differentiate between methods and constructors in Java, and illustrate with a program how
constructors (including overloaded ones) are invoked along with method calls in object creation.
Ans:
Difference between methods and constructors

Methods Constructors
1. A method is a block of code or collection 1. A constructor initializes an object
of statements or a set of immediately upon creation. It
code grouped together to perform a certain has the same name as the class in which it
task or operation. It is resides and is
used to achieve the reusability of code. syntactically similar to a method.
2. Here, type specifies the type of data 2. Constructors look a little strange
returned by the method. This because they have no return type,
can be any valid type, including class types not even void.Name is same as class name
that you create. If the method does not return
a value, its return type must be void.
The name of the method is specified by name.

public class Box { public class Box {


int width; int width;
// Method // Constructor
void setWidth(int w) { public Box() {
width = w; width = 10;
} }
} }

Example Program – Demonstrating Constructors (including Overloaded) and Methods

class Student {

int id;

String name;

// Default constructor

Student() {

id = 0;

name = "Unknown";

System.out.println("Default constructor called");

// Parameterized constructor

Student(int i, String n) {

id = i;

name = n;

System.out.println("Parameterized constructor called");

// Method to display student details

void display() {
System.out.println(id + " " + name);

class TestStudent {

public static void main(String args[]) {

// Invokes default constructor

Student s1 = new Student();

s1.display();

// Invokes parameterized constructor

Student s2 = new Student(101, "John");

s2.display();

3.Explain how objects are used in method handling by passing them as parameters and returning
them from methods, and justify how this approach enhances code reusability with a suitable Java
program.

Ans:

Objects as Parameters and Return Values in Methods

• In Java, we can pass objects as arguments to methods. This allows methods to operate directly
on object data.
• Methods can also return objects, enabling one method to give an object as output to another.
• This technique enhances code reusability because the same method logic can be applied to
different objects without rewriting code.
Example Program

class Student {

int id;

String name;

Student(int i, String n) {

id = i;

name = n;

// Method that takes object as parameter

void display(Student s) {

System.out.println(s.id + " " + s.name);

// Method that returns object

Student getStudent() {

return this; // returns current object

class Test {

public static void main(String args[]) {

Student s1 = new Student(101, "Alice");

Student s2 = new Student(102, "Bob");


// Passing object as parameter

s1.display(s2); // prints details of s2

// Returning object from method

Student s3 = s1.getStudent();

s3.display(s1); // prints details of s1

Justification (Code Reusability)

• The display() method can print details of any Student object passed to it → no need to write
multiple display methods.
• The getStudent() method can return an object to be reused elsewhere.
• Thus, object passing and returning reduces code duplication and makes the program more
modular and reusable.

4. Explain constructors in Java and discuss their types (default and parameterized). Demonstrate
the concept of constructor overloading with a Ticket Booking System program, including discount
logic. • Design a Java program for Ticket Booking using constructors. The program should: •
Create a default constructor that initializes ticket details with default values. • Use a
parameterized constructor to initialize booking details such as passenger name, source,
destination, and fare. • Implement constructor overloading by allowing tickets to be booked with
and without discounts. • Apply a discount logic (e.g., 10% discount on fare for online booking). •
Display the final ticket details, including passenger name, source, destination, original fare,
discount applied, and final payable fare.

import java.util.Scanner;

class TicketBooking {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Default constructor
Ticket t1 = new Ticket();
t1.displayTicket();

// Parameterized constructor (without discount)


System.out.println("\n--- Book Ticket (Without Discount) ---");
System.out.print("Enter Passenger Name: ");
String name = sc.nextLine();
System.out.print("Enter Source: ");
String source = sc.nextLine();
System.out.print("Enter Destination: ");
String destination = sc.nextLine();
System.out.print("Enter Fare: ");
double fare = sc.nextDouble();
sc.nextLine(); // clear buffer

Ticket t2 = new Ticket(name, source, destination, fare);


t2.displayTicket();

// Parameterized constructor (with discount)


System.out.println("\n--- Book Ticket (With Discount - Online Booking) ---");
System.out.print("Enter Passenger Name: ");
String name2 = sc.nextLine();
System.out.print("Enter Source: ");
String source2 = sc.nextLine();
System.out.print("Enter Destination: ");
String destination2 = sc.nextLine();
System.out.print("Enter Fare: ");
double fare2 = sc.nextDouble();

Ticket t3 = new Ticket(name2, source2, destination2, fare2, true);


t3.displayTicket();

sc.close();
}
}

class Ticket {
String passengerName;
String source;
String destination;
double fare;
double finalFare;
boolean discountApplied;

// Default constructor
Ticket() {
passengerName = "Unknown";
source = "Not Specified";
destination = "Not Specified";
fare = 0.0;
finalFare = fare;
discountApplied = false;
System.out.println("\nDefault Ticket Created.");
}

// Parameterized constructor without discount


Ticket(String passengerName, String source, String destination, double fare) {
this.passengerName = passengerName;
this.source = source;
this.destination = destination;
this.fare = fare;
this.finalFare = fare;
this.discountApplied = false;
System.out.println("\nTicket Created Without Discount.");
}

// Parameterized constructor with discount (Overloaded)


Ticket(String passengerName, String source, String destination, double fare, boolean onlineBooking)
{
this.passengerName = passengerName;
this.source = source;
this.destination = destination;
this.fare = fare;

if (onlineBooking) {
this.finalFare = fare - (fare * 0.10); // 10% discount
this.discountApplied = true;
} else {
this.finalFare = fare;
this.discountApplied = false;
}
System.out.println("\nTicket Created With Discount (Online Booking).");
}

// Display Ticket details


void displayTicket() {
System.out.println("\n--- Ticket Details ---");
System.out.println("Passenger Name : " + passengerName);
System.out.println("Source : " + source);
System.out.println("Destination : " + destination);
System.out.printf("Original Fare : %.2f\n", fare);
System.out.println("Discount : " + (discountApplied ? "10% Applied" : "No Discount"));
System.out.printf("Final Fare : %.2f\n", finalFare);
}
}

5. Explain the concept of Garbage Collection in Java, compare it with memory management in
C++, and evaluate its role in ensuring efficient memory utilization in large applications.

Ans:

Garbage Collection vs Memory Management in C++


Aspect Java (Garbage Collection) C++ (Manual Management)

Memory
Automatic by JVM Garbage Collector Manual using delete()
release

Complex → programmer must


Ease of use Simple → no explicit memory handling
manage

Error Risk of memory leaks, dangling


Prevents memory leaks and dangling pointers
handling pointers

Less programmer control over exact time of


Control Full programmer control
memory release

Role in Large Applications

• Efficiency: GC automatically frees unused memory, reducing the chance of memory leaks.
• Reliability: Applications become more robust since developers don’t need to manually track
memory usage.
• Scalability: In large, complex applications (like servers, databases, enterprise software), GC
ensures smooth performance by recycling memory.
• Focus on Logic: Developers can concentrate on problem-solving instead of debugging memory
issues.

6. Discuss the use of the static and final keywords in Java, illustrate their role with suitable
programs, and analyze their impact on object-oriented programming design.

Ans:

Static Keyword in Java

• The static keyword allows class members (variables and methods) to be accessed without
creating objects.
• Static Variables: Shared by all instances of the class (only one copy exists).
• Static Methods: Can be called without object creation, but they:
o Can only directly access other static members.
o Cannot use this or super.
• Static Block: Runs once when the class is loaded, useful for initialization.

Example:

class UseStatic {

static int a = 3;

static int b;

static void meth(int x) {

System.out.println("x = " + x);

System.out.println("a = " + a);

System.out.println("b = " + b);

// Static block
static {

System.out.println("Static block initialized.");

b = a * 4;

public static void main(String args[]) {

meth(42);

Output:

Static block initialized.

x = 42

a=3

b = 12

Final Keyword in Java

• Used to declare constants, prevent inheritance, or prevent method overriding.


• Final Variables: Value cannot be changed once assigned.
• Final Methods: Cannot be overridden in a subclass.
• Final Classes: Cannot be inherited.

Example

class FinalDemo {

final int FILE_OPEN = 2;

void show() {

System.out.println("Constant value: " + FILE_OPEN);

}
}

class TestFinal {

public static void main(String args[]) {

FinalDemo f = new FinalDemo();

f.show();

Impact on Object-Oriented Programming Design

• static
o Promotes memory efficiency by sharing variables across objects.
o Useful for utility methods (e.g., Math.sqrt() in Java).
o Reduces object dependency when behavior is class-level rather than object-level.
• final
o Ensures immutability of values (important in secure applications).
o Enforces design constraints: prevents unwanted inheritance or method modification.
o Helps maintain consistent behavior across the program.

7.Explain the fundamentals of Strings in Java, demonstrate at least five important String methods
with examples, and analyse how immutability and memory management affects string handling
and performance

Fundamentals of Strings in Java

• In Java a string is a sequence of characters.

• Unlike some other languages that implement strings as character arrays, Java implements strings
as objects of type String.

• A string in Java is immutable – once a String object has been created, you cannot change its
characters.

• When a modification is performed, a new String object is created that contains the modified
value, while the original string remains unchanged.

• To handle modifiable strings, Java provides StringBuffer and StringBuilder.


Five Important String Methods
1. toLowerCase() / toUpperCase()
Converts the string s1 to all lowercase
Converts the string s1 to all uppercase
String s1 = "Java";
String s2 = s1.toLowerCase();
String s3 = s1.toUpperCase();
2. equals() and equalsIgnoreCase()
Returns ‘true’ if s1 is equal to s2
Returns ‘true’ if s1=s2 ignoring the case of characters
String s1 = "Java";
String s2 = "java";
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
3. length()
Gives the length of s1
String s1 = "Hello World";
System.out.println(s1.length()); // 11
4. charAt()
Gives nth character of s1
String s1 = "Java";
System.out.println(s1.charAt(2)); // v
5. substring()
Gives substring starting from nth character.
s1.substring(n,m) Gives substring starting from nth character upto mth (not including mth)
String s1 = "Programming";
System.out.println(s1.substring(3)); // "gramming"
System.out.println(s1.substring(0, 6)); // "Progra"

Immutability and Memory Management

Since String objects are immutable, they cannot be changed once created.

• If you modify a string, a new object is created and the old one is left for garbage collection.

• This immutability improves performance in string handling because:


o Strings can be safely shared between multiple references.

o JVM maintains a String pool (intern pool), so identical string literals are stored only
once, reducing memory usage.
• For frequent modifications (e.g., appending, inserting), using StringBuffer or StringBuilder is
more efficient because they are mutable.
8. Differentiate between String and StringBuffer classes with examples, demonstrate append(), insert(), and
delete() methods of StringBuffer, and evaluate how StringBuffer improves efficiency in string
manipulation. Design a Java program to manage student remarks using StringBuffer. The program
should:
a. Start with a remark "Student performance: ".
b. Append the student's grade (e.g., "Excellent").
c. Insert the student’s name at the beginning of the remark.
d. Delete unnecessary words (e.g., remove "performance" if not required).
e. Display the final remark.

Difference between String and StringBuffer


String StringBuffer
Strings are immutable (cannot be changed
StringBuffer objects are mutable (can be modified).
after creation).
Every modification creates a new String Modifications happen on the same object, no new object
object, old one is left unused. is created.
Less efficient when many modifications are More efficient for frequent changes like append, insert,
needed (concatenation, insertion). delete.
Defined in java.lang.String class. Defined in java.lang.StringBuffer class.
Example: String s = "Java"; s = s + " Example: StringBuffer sb = new StringBuffer("Java");
Program"; creates a new object. sb.append(" Program"); modifies same object.

Important Methods of StringBuffer


1. append()
• Appends a string (or other data type) to the end of the buffer.
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
Output:
Hello World

2. insert()
• Inserts a string at a specified index.
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
Output:
I like Java!

3. delete()
• Deletes characters from a start index up to (but not including) an end index.
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(5, 7);
System.out.println(sb);
Output:
This a test.

Efficiency of StringBuffer
• Because String objects are immutable, every change creates a new object, which wastes
memory and reduces performance when handling large or frequently modified strings.
• StringBuffer, being mutable, modifies the same object in place.
• It also has extra pre-allocated capacity to minimize reallocation during modifications.
• This makes it more memory-efficient and faster for operations like appending, inserting, or
deleting strings.

import java.util.Scanner;

class StudentRemarks {
StringBuffer remark;

// Initialize with base remark


void initializeRemark() {
remark = new StringBuffer("Student performance: ");
System.out.println("Initial Remark: " + remark);
}

// Append grade to remark


void appendGrade(Scanner sc) {
System.out.print("Enter grade to append: ");
String grade = sc.nextLine();
remark.append(grade);
System.out.println("After append: " + remark);
}

// Insert student name at beginning


void insertName(Scanner sc) {
System.out.print("Enter student name: ");
String name = sc.nextLine();
remark.insert(0, name + " - ");
System.out.println("After insert: " + remark);
}
// Delete a word from remark
void deleteWord(Scanner sc) {
System.out.print("Enter start index to delete: ");
int start = sc.nextInt();
System.out.print("Enter end index to delete: ");
int end = sc.nextInt();
sc.nextLine(); // clear newline
remark.delete(start, end);
System.out.println("After delete: " + remark);
}

// Display final remark


void displayFinalRemark() {
System.out.println("Final Remark: " + remark);
}
}

public class StudentRemarksTest {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

StudentRemarks sr = new StudentRemarks();


sr.initializeRemark(); // Step a
sr.appendGrade(sc); // Step b
sr.insertName(sc); // Step c
sr.deleteWord(sc); // Step d
sr.displayFinalRemark(); // Step e

sc.close();
}
}

9.Explain the concepts of method overloading and method overriding in Java with suitable
programs. Demonstrate how method overloading achieves compile-time polymorphism with an
example.

Method Overloading:
In Java, it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different.

When this is the case, the methods are said to be overloaded, and the process is referred to as method
overloading.

Method overloading is one of the ways that Java supports polymorphism.

Overloaded methods must differ in the type and/or number of their parameters.

The return type alone is not sufficient to distinguish overloaded method.

Program – Method Overloading


class OverloadDemo {
void test() {
System.out.println("No parameters");
}

void test(int a) {
System.out.println("a: " + a);
}

void test(int a, int b) {


System.out.println("a and b: " + a + " " + b);
}

double test(double a) {
System.out.println("double a: " + a);
return a * a;
}
}

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

ob.test(); // No parameters
ob.test(10); // One int parameter
ob.test(10, 20); // Two int parameters
result = ob.test(123.25); // One double parameter

System.out.println("Result of ob.test(123.25): " + result);


}
}
Output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Shows compile-time polymorphism (method selection done by compiler based on arguments).

Method Overriding

• When a subclass defines a method that has the same name, return type, and parameters as a
method in its superclass, then the subclass method overrides the superclass method.

• Overriding allows a subclass to provide a specific implementation of a method already


defined in its superclass.

• The version of the method that is executed is determined at runtime, based on the type of the
object. This is runtime polymorphism.

o .

Program – Method Overriding


class A {
void show() {
System.out.println("This is superclass method");
}
}

class B extends A {
// Overriding method
void show() {
System.out.println("This is subclass method");
}
}

class OverrideDemo {
public static void main(String args[]) {
A obj = new B(); // reference of superclass, object of subclass
obj.show(); // calls subclass method
}
}
Output:

This is subclass method


Method Overloading and Compile-Time Polymorphism

• Definition: Method overloading means having multiple methods with the same name in the
same class but with different parameter lists (number or type of arguments).
• The compiler decides at compile-time which version of the method to call → this is called
compile-time polymorphism.
• The return type alone cannot differentiate overloaded methods.

10. Explain the purpose of the StringTokenizer class in Java, discuss its constructors and key methods, and
demonstrate its usage in parsing a sentence into words with a program. A library system needs to parse a
string containing book details (title, author, and year) separated by commas. Write a program using
StringTokenizer that:
a. Reads the string "Java The Complete Reference,Herbert Schildt,2024".
b. Extracts each token (book title, author name, and year).
c. Displays them neatly.

StringTokenizer:
• The processing of text often consists of parsing a formatted input string.
• Parsing = dividing text into a set of discrete parts (tokens) that convey meaning.
• The StringTokenizer class provides the first step in this parsing process (lexer or scanner).
• It implements the Enumeration interface.
• Given an input string, it allows us to enumerate the individual tokens contained in it.
Delimiters:
• Tokens are separated by delimiters (characters like , ; :).
• The default delimiters are whitespace characters: space, tab, form feed, newline, carriage return.
Program:
import java.util.Scanner;
import java.util.StringTokenizer; // only this import is added

class Book {
// Instance variables
private String bookName;
private String authorName;
private String year; // replaced isbnNumber & publisher with year

// Constructor
public Book(String bookName, String authorName, String year) {
this.bookName = bookName;
this.authorName = authorName;
this.year = year;
}

// Setters (Mutators)
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public void setYear(String year) {
this.year = year;
}

// Getters (Accessors)
public String getBookName() {
return this.bookName;
}
public String getAuthorName() {
return this.authorName;
}
public String getYear() {
return this.year;
}

// Method to return book information as a formatted string


public String getBookInfo() {
return "Book Name: " + this.bookName + "\n" +
"Author : " + this.authorName + "\n" +
"Year : " + this.year;
}
}

public class BookTest {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Instead of asking for multiple books, just parse one string


String bookDetails = "Java The Complete Reference,Herbert Schildt,2024";

// Use StringTokenizer to split the details


StringTokenizer st = new StringTokenizer(bookDetails, ",");
String bookName = st.nextToken();
String author = st.nextToken();
String year = st.nextToken();
// Create one Book object with parsed values
Book book = new Book(bookName, author, year);

// Display details
System.out.println("\n--- Book Details ---");
System.out.println(book.getBookInfo());

sc.close();
}
}

11.Explain the concept of nested and inner classes?

In Java, it is possible to define a class within another class. Such classes are called nested classes.

The scope of a nested class is bounded by the scope of its enclosing class.

If class B is defined within class A, then B does not exist independently of A.


A nested class has access to the members (including private members) of its enclosing class.
However, the enclosing class does not have access to the members of the nested class.
Types of nested classes:
1. Static Nested Class – declared with the static modifier. It cannot directly access non-static
members of its enclosing class (must use an object).
2. Inner Class (non-static nested class) – has access to all variables and methods of the outer class
and may refer to them directly.
Example:
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}

// this is an inner class


class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}

class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output:display: outer_x = 100

12.Explain multilevel inheritance in Java with a program, highlighting the sequence of constructor
calls and order of execution. Demonstrate the use of the super keyword for accessing superclass
members and constructors, and differentiate it from the this keyword Design a University
Administration System in Java to manage staff records. The system should model both Teaching
Staff and Non-Teaching Staff, sharing common details (name, ID, salary) while maintaining
category-specific information. Implement single, multilevel, and hierarchical inheritance, and
demonstrate the use of the super keyword for invoking superclass methods and constructors. The
program must accept user input to create and display records for different staff types.

Multilevel Inheritance means a class is derived from a subclass, making a chain of inheritance.
Example: A → B → C.

• When objects of the most derived class (C) are created, constructors are called in order of
inheritance:
1. Superclass constructor (A)
2. Intermediate class constructor (B)
3. Subclass constructor (C)
super keyword:
• When a subclass constructor is invoked, it can call its immediate superclass constructor using
super()
• Used to access superclass methods/variables that are hidden by subclass.
this keyword:
• Refers to the current object.
• Used to distinguish instance variables and parameters with the same name.
• Can be passed to methods/constructors or returned from a method.
• Difference between super and this

Keyword Refers to Usage


- Call parent constructor (super())
super Immediate parent class object
- Access hidden parent variables/methods
- Call current class constructor (this())
this Current class object - Access current class variables/methods
- Differentiate instance variables from parameters
import java.util.Scanner;

// Super class
class Staff
{
String name;
int staffId;
double baseSalary;

Staff(String name, int staffId, double baseSalary)


{
this.name = name;
this.staffId = staffId;
this.baseSalary = baseSalary;
}

void displayDetails()
{
System.out.println("Name : " + name);
System.out.println("Staff ID : " + staffId);
System.out.println("Base Salary: " + baseSalary);
}
}

// Subclass demonstrating single inheritance


class TeachingStaff extends Staff
{
String subject;
int experience;

TeachingStaff(String name, int staffId, double baseSalary, String subject, int experience)
{
super(name, staffId, baseSalary);
this.subject = subject;
this.experience = experience;
}

void displayDetails()
{
super.displayDetails(); // Calling super class method
System.out.println("Subject : " + subject);
System.out.println("Experience: " + experience + " years");
}
}

// Subclass class from TeachingStaff demonstrating multilevel inheritance


class HOD extends TeachingStaff
{
String department;

HOD(String name, int staffId, double baseSalary, String subject, int experience, String
department)
{
super(name, staffId, baseSalary, subject, experience);
this.department = department;
}

void displayDetails()
{
super.displayDetails(); // Calling superclass method
System.out.println("Department: " + department);
}
}

// Another sub class demonstrating hierarchical inheritance


class NonTeachingStaff extends Staff
{
String workType;

NonTeachingStaff(String name, int staffId, double baseSalary, String workType)


{
super(name, staffId, baseSalary);
this.workType = workType;
}

void displayDetails()
{
super.displayDetails(); // Accessing superclass method
System.out.println("Work Type : " + workType);
}
}
public class UniversityStaffDemo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("--------- University Staff Record ---------");


System.out.println("1. Teaching Staff");
System.out.println("2. HOD");
System.out.println("3. Non-Teaching Staff");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
sc.nextLine(); // consume newline

switch (choice)
{
case 1:
System.out.print("Enter Name: ");
String tName = sc.nextLine();
System.out.print("Enter Staff ID: ");
int tId = sc.nextInt();
System.out.print("Enter Base Salary: ");
double tSalary = sc.nextDouble();
sc.nextLine();
System.out.print("Enter Subject: ");
String tSubject = sc.nextLine();
System.out.print("Enter Experience (in years): ");
int tExp = sc.nextInt();

TeachingStaff teacher = new TeachingStaff(tName, tId, tSalary, tSubject, tExp);


System.out.println("\n--- Teaching Staff Details ---");
teacher.displayDetails();
break;

case 2:
System.out.print("Enter Name: ");
String hName = sc.nextLine();
System.out.print("Enter Staff ID: ");
int hId = sc.nextInt();
System.out.print("Enter Base Salary: ");
double hSalary = sc.nextDouble();
sc.nextLine();
System.out.print("Enter Subject: ");
String hSubject = sc.nextLine();
System.out.print("Enter Experience (in years): ");
int hExp = sc.nextInt();
sc.nextLine();
System.out.print("Enter Department: ");
String hDept = sc.nextLine();

HOD hod = new HOD(hName, hId, hSalary, hSubject, hExp, hDept);


System.out.println("\n--- HOD Details ---");
hod.displayDetails();
break;

case 3:
System.out.print("Enter Name: ");
String nName = sc.nextLine();
System.out.print("Enter Staff ID: ");
int nId = sc.nextInt();
System.out.print("Enter Base Salary: ");
double nSalary = sc.nextDouble();
sc.nextLine();
System.out.print("Enter Work Type: ");
String nWork = sc.nextLine();

NonTeachingStaff nonTeaching = new NonTeachingStaff(nName, nId, nSalary,


nWork);
System.out.println("\n--- Non-Teaching Staff Details ---");
nonTeaching.displayDetails();
break;

default:
System.out.println("Invalid choice.");
}

sc.close();
}
}

You might also like