0% found this document useful (0 votes)
14 views7 pages

Single Inheritance Single Inheritance Is A Foundational Concept in Object

The document discusses various inheritance types in object-oriented programming, including Single, Multilevel, and Hierarchical Inheritance, highlighting their structures and benefits for code reusability and organization. It also covers the MVC architecture, explaining the roles of Model, View, and Controller in application design. Additionally, it provides Java programming examples for GUI applications, file handling, and exception management.

Uploaded by

maheshnile15736
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)
14 views7 pages

Single Inheritance Single Inheritance Is A Foundational Concept in Object

The document discusses various inheritance types in object-oriented programming, including Single, Multilevel, and Hierarchical Inheritance, highlighting their structures and benefits for code reusability and organization. It also covers the MVC architecture, explaining the roles of Model, View, and Controller in application design. Additionally, it provides Java programming examples for GUI applications, file handling, and exception management.

Uploaded by

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

Single Inheritance Single Inheritance is a foundational concept in object-oriented programming (OOP) where a

class can inherit attributes and behaviors from only one parent or base class. This creates a linear hierarchy,
simplifying the structure and reducing the potential for conflicts. It promotes code reusability, as a derived class
can extend and specialize the functionality of a single parent class. The simplicity of Single Inheritance makes it a
widely adopted and easily comprehensible paradigm in OOP, facilitating the organization of code and fostering
maintainability..
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
Multilevel Inheritanc: Multilevel Inheritance involves a chain of classes where each class, except the first one,
serves as both a derived class and a base class for the next one in the chain. This creates a hierarchical structure,
allowing for incremental specialization of functionality. The multilevel nature of this inheritance paradigm
facilitates the organization of code and the creation of well-defined class relationships, promoting modularity and
code reuse
class A {
void methodA() {
System.out.println("Method A");
}
}

class B extends A {
void methodB() {
System.out.println("Method B");
}
}
class C extends B {
void methodC() {
System.out.println("Method C");
}
}
Hierarchical Inheritance: Hierarchical Inheritance is characterized by multiple classes inheriting from a common
base class. This forms a tree-like structure, with the base class at the root and derived classes as branches. The
shared base class allows for the inheritance of common attributes and behaviors, promoting a consistent design
pattern. Hierarchical Inheritance enhances code organization, fosters reusability, and provides a clear
representation of class relationships in a program..
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
void drawCircle() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
void drawSquare() {
System.out.println("Drawing a square");
}
}
}
Write a Program to illustrate multilevel Define abstract class shape with Write a Java Program to copy the contents form
Inheritance such that country is inherited abstract method area (). Write a java one file into another file. While copying, change
from continent. State is inherited from program to calculate area of circle. the case of cell the alphabets & replace all the
country. Display the place, state, country import java.util.*; digital by '*'
and continent. interface Shape { import java.io.*;
import java.util.*; double area(); public class FileCopy {
class continent { } public static void main(String[] args) {
String c1; String in = "input.txt";
} class Triangle implements Shape { String out = "output.txt";
class country extends continent { double base; try {
double height; copy (in, out);
String c2;
System.out.println("Content copied, case
}
public Triangle(double base, changed, and digits replaced successfully.");
class state extends country { double height) { } catch (IOException e) {
String s1; this.base = base; System.err.println("Error: " + e.getMessage());
String p1; this.height = height; }
public void display() { } }
System.out.println("Continent name: " + c1
+ "\n" +"Country name: " + c2 + "\n" + @Override private static void copy (String in, String out) throws
"State Name: " + s1 + "\n" +"Place: " + p1); public double area() { IOException {
} return 0.5 * base * height; try (FileReader r = new FileReader(in);
public static void main(String args[]) { } FileWriter w = new FileWriter(out)) {
state ob = new state(); }
Scanner sc = new Scanner(System.in); int c;
public class Main { while ((c = r.read()) != -1) {
public static void main(String[] char m = modifyCharacter((char) c);
System.out.println("Enter the
args) { w.write(m);
continent"); Triangle triangle = new }
ob.c1 = sc.next(); Triangle(5.0, 8.0); }
System.out.println("Enter the Country"); System.out.println("Area of the }
ob.c2 = sc.next(); Triangle: " + triangle.area());
System.out.println("Enter the state"); } private static char modifyCharacter(char c) {
ob.s1 = sc.next(); } if (Character.isUpperCase(c)) {
System.out.println("Enter the place"); return Character.toLowerCase(c);
ob.p1 = sc.next(); } else if (Character.isLowerCase(c)) {
return Character.toUpperCase(c);
ob.display(); } else if (Character.isDigit(c)) {
return '*';
}
} else {
}
return c;
}
}
}
Explain MVC architecture in details.

1. Model:The Model represents the application's data and business logic. It is responsible for managing
the data, processing user inputs, and updating the state of the application. The model notifies the view
whenever there is a change in the data, and it also receives input from the controller.
2. View:The View is responsible for presenting the data to the user and receiving user inputs. It represents
the user interface elements such as buttons, text fields, and other graphical elements. The view gets its
data from the model but does not directly interact with the model.
3. Controller:The Controller acts as an intermediary between the Model and the View. It receives user
inputs from the view, processes them (possibly updating the model), and then updates the view
accordingly. The controller interprets user actions and translates them into actions on the model.
1. The user interacts with the View by providing input.
2. The View sends the input to the Controller.
3. The Controller processes the input, updating the Model accordingly.
4. The Model notifies the View of the changes in the data.
5. The View fetches the updated data from the Model and displays it to the user.
Write a Java program using AWT to change Write a java program using swing to accept details of employee (eno,
background color of table to 'RED' by clicking on ename, esal) and display it by clicking on a button
button,the background of TextField by clicking on import javax.swing.*;
a button import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.*; import java.awt.event.ActionListener;
import java.awt.event.*; public class EmployeeDetailsGUI extends JFrame {
private JTextField enoField, enameField, esalField;
public class ColorChangeProgram extends Frame { private JTextArea resultArea;
private Button changeColorButton; public EmployeeDetailsGUI() {
private Panel panel; setTitle("Employee Details");
private TextField textField; setSize(400, 300);
public ColorChangeProgram() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Color Change Program"); enoField = new JTextField(10);
setSize(400, 200); enameField = new JTextField(10);
changeColorButton = new Button("Change Color"); esalField = new JTextField(10);
panel = new Panel(); resultArea = new JTextArea(10, 30);
textField = new TextField("Type here"); resultArea.setEditable(false);
setLayout(new BorderLayout()); JButton displayButton = new JButton("Display Details");
add(changeColorButton, BorderLayout.NORTH); displayButton.addActionListener(new ActionListener() {
add(panel, BorderLayout.CENTER); @Override
panel.add(textField); public void actionPerformed(ActionEvent e) {
changeColorButton.addActionListener(new displayDetails();
ActionListener() { } }); setLayout(new GridLayout(4, 2));
@Override add(new JLabel("Employee Number: "));
public void actionPerformed(ActionEvent e) { add(enoField);
panel.setBackground(Color.RED); add(new JLabel("Employee Name: "));
textField.setBackground(Color.RED); add(enameField);
} add(new JLabel("Employee Salary: "));
}); add(esalField);
add(displayButton);
addWindowListener(new WindowAdapter() { add(resultArea);
public void windowClosing(WindowEvent we) { } private void displayDetails() {
dispose(); String eno = enoField.getText();
} String ename = enameField.getText();
}); String esal = esalField.getText();
} String result = "Employee Details:\n" +
public static void main(String[] args) { "Employee Number: " + eno + "\n" +
ColorChangeProgram frame = new "Employee Name: " + ename + "\n" +
ColorChangeProgram(); "Employee Salary: " + esal;
frame.setVisible(true); resultArea.setText(result);
} }
} public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
newEmployeeDetailsGUI().setVisible(true);
}
});
Write a program to accept a string as Write a Java program to Read the file and display of screen
command line argument and check whether accept a number from user. import java.io.*;
it is a file or directory. Also perform If it is zero then throw user
operations as follows: i)If it is a defined exception "Number class Display {
directory,delete all text files in that directory. public static void main(String[] args) throws
is zero". Otherwise calculate
import java.util.*; Exception {
its factorial
import java.io.*; FileInputStream f1 = new
mport java.util.Scanner;
FileInputStream("temp.txt");
class NumberIsZeroException
class slip27_2 { int n;
extends Exception {
public static void main(String[] args) {
public
Scanner sc = new Scanner(System.in); System.out.println("Total bytes available in
NumberIsZeroException(String
String fname = args[0]; // Takes the file file: " + f1.available());
message) {
name as a command line argument
super(message);
File f = new File(fname); while ((n = f1.read()) != -1) {
}
System.out.print((char) n);
}
if (f.isFile()) { }
public class FactorialCalculator {
System.out.println("File Name: " + f1.close();
public static void main(String[]
f.getName()); }
args) {
System.out.println("File Length: " + }
Scanner scanner = new
f.length());
Scanner(System.in);
System.out.println("File Absolute Path: Crete file and disply read and write
" + f.getAbsolutePath()); import java.io.*;
try {
System.out.println("File Path: " +
System.out.print("Enter a
f.getPath()); class FileRead {
number: ");
} else if (f.isDirectory()) { public static void main(String args[]) throws
int number =
Exception {
scanner.nextInt();
System.out.println("Sure you want FileWriter f1 = new FileWriter("data.txt");
Delete All Files (Press 1)"); BufferedReader br = new
if (number == 0) {
int n = sc.nextInt(); BufferedReader(new
throw new
InputStreamReader(System.in));
NumberIsZeroException("Number
if (n == 1) { int ch;
is zero");
String[] s1 = f.list();
} else {
String a = ".txt"; System.out.println("Enter integers, enter -1
long factorial =
to stop:");
calculateFactorial(number);
for (String str : s1) {
System.out.println(str); do {
System.out.println("Factorial of "
ch = Integer.parseInt(br.readLine());
+ number + " is: " + factorial);
if (str.endsWith(a)) { f1.write(ch);
}
File f1 = new File(fname, str); } while (ch != -1);
} catch
System.out.println(str + "--
(NumberIsZeroException e) {
>Deleted"); f1.close();
f1.delete();
System.out.println("Exception: " +
} FileReader f2 = new FileReader("data.txt");
e.getMessage());
} while ((ch = f2.read()) != -1) {
} catch (Exception e) {
} else { System.out.print((char) ch);
System.out.println("Error:
System.out.println("OKKKK"); }
" + e.getMessage());
} f2.close();
} finally {
} }
scanner.close();
} }
}
}
}
private static long
calculateFactorial(int n) {
if (n == 1 || n == 0) {
return 1;
} else {
return n *
calculateFactorial(n - 1);
}
}
}

FLOW GRid BOX


import java.awt.*; import java.awt.*; import java.awt.*;
import java.applet.*; import java.applet.*; import javax.swing.*;
import java.awt.event.*;
public class FlowApplet extends public class BoxDemo extends Frame {
Applet { /* <applet code="grid.class" Button[] b;
TextField t1, t2, t3; width=250 height=250></applet> */
public class grid extends Applet public BoxDemo() {
public void init() { implements ActionListener { b = new Button[5];
setLayout(new TextField t1, t2, t3;
FlowLayout(FlowLayout.RIGHT)); Label l1; for (int i = 0; i < 5; i++) {
Button b1; b[i] = new Button("Button " + (i
t1 = new TextField(30); + 1));
t2 = new TextField(30); public void init() { add(b[i]);
t3 = new TextField(30); setLayout(new GridLayout(5, 1)); }
t1 = new TextField(30);
add(t1); t2 = new TextField(30); setLayout(new BoxLayout(this,
add(t2); t3 = new TextField(30); BoxLayout.Y_AXIS));
add(t3); l1 = new Label("*", setSize(400, 400);
} Label.CENTER); setVisible(true);
} b1 = new Button("="); }
b1.addActionListener(this);
Border add(t1); public static void main(String args[])
import java.awt.*; add(l1); {
import java.applet.*; add(t2); BoxDemo box = new BoxDemo();
import java.awt.event.*; add(b1); box.addWindowListener(new
add(t3); WindowAdapter() {
public class BorderApplet extends } public void
Applet implements ActionListener { windowClosing(WindowEvent
Button b1, b2, b3, b4; public void windowEvent) {
TextField t1; actionPerformed(ActionEvent e) { System.exit(0);
try { }
public void init() { int x = });
setLayout(new BorderLayout()); Integer.parseInt(t1.getText()); }
int y = }
b1 = new Button("B1"); Integer.parseInt(t2.getText()); Write a program to accept
b2 = new Button("B2"); two no from command line
b3 = new Button("B3"); if (e.getSource() == b1) {
b4 = new Button("B4"); int z = x * y; perform their addition and
t1 = new TextField(30); t3.setText("Multiplication is " substraction
+ z); class Operation {
add("North", b1); } int a, b;
void accept(int p, int q) {
add("South", b2); } catch (NumberFormatException
a = p;
add("East", b3); ex) { b = q;
add("West", b4); // Handle the case where the }void cal() {
add("Center", t1); input is not a valid integer int ans = a + b;
t3.setText("Invalid input. int ans1 = a - b;
b1.addActionListener(this); Please enter valid integers."); System.out.println("Addition is: " +
b2.addActionListener(this); } ans);
b3.addActionListener(this); } System.out.println("Subtraction is: " +
ans1);
b4.addActionListener(this); }
}
} }class Test_22 {
public static void main(String args[]) {
public void int x = Integer.parseInt(args[0]);
actionPerformed(ActionEvent e) { int y = Integer.parseInt(args[1]);
String s = Operation t = new Operation();
e.getActionCommand(); t.accept(x, y);
t1.setText("You clicked on " + s); t.cal();
}
}
}
1. Exception: • Exception:
• Definition: An event that disrupts the • Answer: An event during program execution
normal flow of a program during execution, that disrupts the normal flow due to errorsg)
typically due to errors. • Package:
2. Interface: • Answer: A way to organize related classes
• Definition: A collection of abstract and interfaces in Java to improve code
methods providing a contract for organization.
implementing classes in Java. • Use of new Operator:
3. Javadoc: • Answer: Used to create an instance (object)
• Definition: A documentation generator of a class in Java.
tool in Java for creating HTML • Functional Interface:
documentation from code comments. • Definition: An interface with a single
4. AWT (Abstract Window Toolkit): abstract method, often used with lambda
• Definition: A set of GUI components in expressions.
Java for creating graphical user interfaces. • Unchecked Exception:
5. Static Keyword: • Definition: Exceptions that do not need to
• Definition: Used to create class-level be declared in a method's signature or
members, shared among all instances of a handled explicitly.
class. • Opening File in Read Mode:
6. Command Line Argument: • Answer: Use FileReader or BufferedReader
to open a file in read mode.
• Definition: Parameters provided to a
program when it is executed from the
• AWT (Abstract Window Toolkit):
command line. • Answer: A set of GUI components in Java
for creating graphical user interfaces.
7. Types of Constructor:
• Adaptor Class:
• Default Constructor
• Answer: A class that provides default
• Parameterized Constructor
implementations for listener interfaces in
• Copy Constructor
Java, allowing selective implementation by
8. Package:
subclasses.
• Definition: A way to organize related
classes and interfaces in Java to improve • Swing:
code organization. • Explanation: Swing is a set of GUI (Graphical
9. How to Open a File in Read Mode: User Interface) components for Java that
• Answer: Use FileInputStream to open a provides a rich set of user interface elements. It is
part of the Java Foundation Classes (JFC) and is
file in read mode.
used to create desktop applications with
10. Listeners:
graphical interfaces.
• Answer:
• BufferedReader:
• ActionListener
• Explanation: BufferedReader is a class in Java
• MouseListener
that provides efficient reading of characters,
11. Use of Javac:
arrays, or lines from a character-input stream. It
• Answer: Java compiler used to translate Java
makes the performance of reading text from a
source code into bytecode.
source more efficient by buffering the characters.
12. Wrapper Classes:
• Inner Class:
• Answer:
• Explanation: An inner class in Java is a class
• Integer
defined within another class. It has access to the
• Double
members of the outer class, including private
13. Use of 'implements' Keyword:
members. Inner classes are often used for
• Answer: Used to declare that a class
encapsulation and organizing code.
implements an interface in Java.
• File Class:
14. Use of Array:
• Explanation: File class in Java is part of the
• Answer: Used to store multiple values of the
java.io package and provides methods for
same data type in a single variable.
working with files and directories. It can be used

You might also like