0% found this document useful (0 votes)
32 views18 pages

Java Constructors, Inheritance, and I/O

The document explains various Java concepts including constructors, constructor overloading, inheritance, file handling, Swing layouts, command line arguments, event handling, interfaces, and packages. It provides examples of Java programs demonstrating these concepts such as creating a Doctor class, handling mouse events, and using ActionListener in Swing. Additionally, it discusses the process of creating and accessing packages in Java with a sample program.

Uploaded by

yashkhalate672
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)
32 views18 pages

Java Constructors, Inheritance, and I/O

The document explains various Java concepts including constructors, constructor overloading, inheritance, file handling, Swing layouts, command line arguments, event handling, interfaces, and packages. It provides examples of Java programs demonstrating these concepts such as creating a Doctor class, handling mouse events, and using ActionListener in Swing. Additionally, it discusses the process of creating and accessing packages in Java with a sample program.

Uploaded by

yashkhalate672
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

a) What are constructors in Java?

Explain
constructor overloading and how the this
keyword is used in constructors.
1. What is a Constructor?

A constructor in Java is a special method used to initialize objects.


It is called automatically when an object is created using new.

Characteristics:

Constructor name is same as class name.

It does not have a return type (not even void).

It is executed only once per object, at the time of creation.

Example:

class Student {
int id;
String name;

// Constructor
Student() {
id = 1;
name = "Yash";
}
}

2. Constructor Overloading

Constructor Overloading means having multiple constructors in the same class


with the same name but different parameter lists (number or type of parameters).

This allows us to create objects in different ways.

Example:

class Student {
int id;
String name;
Student() {
id = 0;
name = "Unknown";
}
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
}

Here:

Student() and Student(int, String) are overloaded constructors.

3. Use of this keyword in Constructors

The this keyword is used in constructors in two main ways:

i) To refer to current object’s instance variables

When parameter names are same as instance variable names, this helps to avoid
confusion.

class Student {
int id;
String name;

Student(int id, String name) {


[Link] = id;
[Link] = name;
}
}

ii) To call another constructor (Constructor Chaining)

We can use this() inside a constructor to call another constructor of the same class.

class Student {
int id;
String name;
String course;

Student() {
this(0, "Unknown"); // calling 2-arg constructor
}

Student(int id, String name) {


[Link] = id;
[Link] = name;
}
}

Rules:

this() call must be the first statement inside the constructor.

It helps in code reuse and avoids repetition.

b) Write a Java program to demonstrate


inheritance and the use of the super keyword.
Inheritance

Inheritance allows one class (child/subclass) to acquire properties and methods of


another class (parent/superclass) using the extends keyword.

super keyword

super is used to:

Call superclass constructor

Access superclass variables or methods when overridden

Example Program

class Animal { // Superclass


String name;

Animal(String name) {
[Link] = name;
[Link]("Animal constructor called");
}

void show() {
[Link]("Animal name: " + name);
}
}
class Dog extends Animal { // Subclass
String breed;

Dog(String name, String breed) {


super(name); // calling parent class constructor
[Link] = breed;
[Link]("Dog constructor called");
}

void showDetails() {
[Link](); // calling parent class method
[Link]("Breed: " + breed);
}
}
class TestInheritance {
public static void main(String[] args) {
Dog d = new Dog("Tommy", "Labrador");
[Link]();
}
}

Explanation

Dog class extends Animal → this is inheritance.

super(name) → calls Animal(String name) constructor.

[Link]() → calls the show() method of Animal class.

Output will show both constructor calls and details.

c) Explain the difference between FileReader and


FileWriter in Java.

Both FileReader and FileWriter are part of [Link] package and work with
character streams (text data).

Feature FileReader FileWriter


Used to read characters from Used to write characters to a
Purpose
a file file
Direction Input (file → program) Output (program → file)
Class Reader (subclass of Writer (subclass of
Type InputStreamReader) OutputStreamWriter)
Feature FileReader FileWriter
Creating or modifying text
Usage Reading text files
files

Example of FileReader

import [Link].*;
class ReadDemo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();
}
}

Example of FileWriter

import [Link].*;
class WriteDemo {
public static void main(String[] args) throws Exception {
FileWriter fw = new FileWriter("[Link]");
[Link]("Hello Java FileWriter!");
[Link]();
}
}

d) What are the different types of layouts in


Swing? Discuss any two of them.
In Swing (and AWT), Layout Managers arrange components in containers like
JFrame, JPanel, etc.

Common Layout Managers


FlowLayout

BorderLayout

GridLayout

BoxLayout
GridBagLayout

CardLayout

GroupLayout (used in GUI builders like NetBeans)

1) FlowLayout

Default layout for JPanel.

Places components in a row (left to right).

If space is not enough, components move to next line.

Components are centered by default.

Example:

import [Link].*;import [Link].*;


class FlowExample {
public static void main(String[] args) {
JFrame f = new JFrame("FlowLayout Example");
[Link](new FlowLayout());

[Link](new JButton("Button 1"));


[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));

[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

2) BorderLayout

Divides container into five regions:


NORTH, SOUTH, EAST, WEST, CENTER.

Each region can contain one component.

Default layout for JFrame’s content pane.

Example:
import [Link].*;import [Link].*;
class BorderExample {
public static void main(String[] args) {
JFrame f = new JFrame("BorderLayout Example");
[Link](new BorderLayout());

[Link](new JButton("North"), [Link]);


[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"),[Link]);

[Link](400, 300);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

e) Explain command line arguments with


suitable example.
What are Command Line Arguments?

Command line arguments are values passed to the main() method when a
Java program is run from the command line.

public static void main(String[] args)

Here, args is a String array that stores the arguments.

Example Program

class CommandLineDemo {
public static void main(String[] args) {
[Link]("Number of arguments: " + [Link]);

for (int i = 0; i < [Link]; i++) {


[Link]("Argument " + i + ": " + args[i]);
}
}
}
Example: Sum of Two Numbers Using Command Line Arguments

class SumCmd {
public static void main(String[] args) {
int a = [Link](args[0]);
int b = [Link](args[1]);

int sum = a + b;
[Link]("Sum = " + sum);
}
}

A) Explain how event handling works in Swing with


an example using ActionListener.

1. What is Event Handling in Swing?


In Swing, event handling means responding to user actions like:

Button click

Menu item click

Enter key in a text field

etc.

Swing uses the Event Delegation Model, which has three main parts:

Event Source – the component that generates the event

e.g., JButton, JTextField, JMenuItem

Event Object – contains information about the event

e.g., ActionEvent, MouseEvent, KeyEvent

Event Listener – an object that waits for the event and handles it

e.g., ActionListener, MouseListener, KeyListener

For button clicks, we normally use ActionListener.

2. What is ActionListener?
ActionListener is an interface in [Link] package.
It has one method:

public void actionPerformed(ActionEvent e)

This method is called automatically when an action event occurs, such as:

Clicking a JButton

Pressing Enter in a JTextField

Choosing a menu item

So, to handle a button click:

Create a class that implements ActionListener

Override actionPerformed() method

Register the listener with the source using addActionListener()

3. Steps of Event Handling with


ActionListener
Create GUI component (event source)
Example: JButton btn = new JButton("Click Me");

Create or implement ActionListener

Either:

class implements ActionListener, or

use anonymous inner class, or

use lambda (Java 8+)

Register listener with source

[Link](listenerObject);

When user clicks the button →


ActionEvent object is created →
actionPerformed() method is called automatically →
Your code inside it runs.
4. Full Example: Button Click using
ActionListener
import [Link].*;import [Link].*;import [Link].*;
class ActionListenerExample extends JFrame implements ActionListener
{

JButton btnClick;
JLabel lblMessage;

ActionListenerExample() {
setTitle("ActionListener Demo");

btnClick = new JButton("Click Me");


lblMessage = new JLabel("Button not clicked yet.");

setLayout(new FlowLayout());

add(btnClick);
add(lblMessage);

[Link](this);

setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


[Link]("Button clicked! Action Performed.");
}

public static void main(String[] args) {


new ActionListenerExample();
}
}
b) Write a Java program to define a class ‘Doctor’
with data members doctorId,doctorName and
doctorSpecialization. Accept the data for ‘n’
objects using array of objects and display it.
import [Link].*;

class Doctor {
int doctorId;
String doctorName, doctorSpecialization;

void getData(Scanner sc) {


[Link]("Enter Doctor ID: ");
doctorId = [Link](); [Link]();
[Link]("Enter Doctor Name: ");
doctorName = [Link]();
[Link]("Enter Specialization: ");
doctorSpecialization = [Link]();
}

void display() {
[Link](doctorId + " " + doctorName + " " +
doctorSpecialization);
}
}

public class DoctorDetails {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of doctors: ");
int n = [Link]();

Doctor d[] = new Doctor[n];


for(int i=0;i<n;i++){
d[i] = new Doctor();
d[i].getData(sc);
}

[Link]("\nDoctor Records:");
for(int i=0;i<n;i++)
d[i].display();
}
}
c) Design a screen in Java using Swing to handle mouse
events such as MOUSE_MOVED and MOUSE_CLICK and display the
x and y co-ordinate of mouse click in a textfield.
import [Link].*;
import [Link].*;
import [Link].*;

class MouseEventDemo extends JFrame implements MouseListener,


MouseMotionListener {

JTextField txtCoord;

MouseEventDemo() {
setTitle("Mouse Event Demo");

txtCoord = new JTextField(20);


[Link](false);

add(txtCoord, [Link]); // add at bottom

addMouseListener(this);
addMouseMotionListener(this);

setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void mouseClicked(MouseEvent e) {


int x = [Link]();
int y = [Link]();
[Link]("Mouse Clicked at: X = " + x + ", Y = " + y);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

public void mouseMoved(MouseEvent e) {


int x = [Link]();
int y = [Link]();
[Link]("Mouse Moved at: X = " + x + ", Y = " + y);
}
public void mouseDragged(MouseEvent e) {}
public static void main(String[] args) {
new MouseEventDemo();
}
}

a) Write a Java program to print the contents form


one file into another file in reverse order.
import [Link].*;

class ReverseFileCopy {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("[Link]");
FileWriter fw = new FileWriter("[Link]");

StringBuilder sb = new StringBuilder();


int ch;

while ((ch = [Link]()) != -1) {


[Link]((char) ch);
}

[Link]();

[Link]([Link]());

[Link]();
[Link]();

[Link]("File copied in reverse order


successfully.");
}
catch(Exception e) {
[Link](e);
}
}
}
b) What is Interface? Explain with example
code.

What is an Interface in Java?


An interface in Java is a blueprint of a class.
It contains abstract methods (without body) and constants.
A class uses the implements keyword to use an interface.

Key points:

Interface contains only abstract methods (Java 8 onwards it may also contain
default, static methods).

Variables in interface are public, static and final by default.

A class must provide implementation of all abstract methods of the


interface.

Interfaces are used to achieve abstraction and multiple inheritance, which


classes cannot do.

Why Interfaces are Used?


To provide standard structure that many classes can follow.

To support multiple inheritance (a class can implement multiple interfaces).

To achieve 100% abstraction.

Example Code of Interface


interface Animal {
void sound();
void eat();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
public void eat() {
[Link]("Dog eats bones");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Animal a = new Dog();
[Link]();
[Link]();
}
}

c) Write a Java program using Swing to create a simple


graphical user interface (GUI) with buttons, labels, and
text fields.
import [Link].*;
import [Link].*;
import [Link].*;

class SimpleGUI extends JFrame implements ActionListener {

JTextField txtName;
JLabel lblResult;
JButton btnShow;

SimpleGUI() {
setTitle("Simple Swing GUI");

JLabel lblName = new JLabel("Enter Name:");


txtName = new JTextField(15);
btnShow = new JButton("Display");
lblResult = new JLabel("Result will appear here.");

[Link](this);

setLayout(new FlowLayout());

add(lblName);
add(txtName);
add(btnShow);
add(lblResult);

setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {


String name = [Link]();
[Link]("Hello, " + name + "!");
}

public static void main(String[] args) {


new SimpleGUI();
}
}

a) Explain the process of creating and accessing packages


in Java. Write a program to demonstrate package usage.

What is a Package in Java?


A package in Java is a collection of related classes and interfaces grouped together.
It helps in:

✔ Organizing code
✔ Avoiding name conflicts
✔ Reusing classes
✔ Improving maintainability

Packages in Java are like folders in a computer system.

Types of Packages in Java


Type Description
Already available in Java (e.g., [Link],
Built-in packages
[Link], [Link], etc.)
User-defined
Created by programmers to group their own classes
packages

Part 1: Creating a Package


Steps to Create a Package

Create a folder (directory)


Create a .java class inside it

Add a package statement at the top of the file

Compile using javac

Example: Creating User-Defined Package

Folder structure:

MyPack
└── [Link]

[Link]

package MyPack;
public class Student {
public void show() {
[Link]("Hello from Student class inside MyPack
package");
}
}

Compile the package:

javac MyPack/[Link]

This compiles and stores .class inside same folder.

Part 2: Accessing Package in Another Program


Create another file outside the package folder:

[Link]

[Link]

import [Link];
class TestPackage {
public static void main(String[] args) {
Student s = new Student();
[Link]();
}
}
b) Write a program that demonstrates the creation
and handling of custom exceptions in Java.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}

public class CustomExceptionDemo {


public static void main(String[] args) {

int age = 15;


try {
if(age < 18) {
throw new InvalidAgeException("Age is less than 18 -
Not Eligible!");
}
else {
[Link]("Age valid ✔ You are eligible!");
}
}
catch(InvalidAgeException e) {
[Link]("Custom Exception Caught:");
[Link]([Link]());
}

[Link]("Program continues normally...");


}
}

You might also like