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

Java OOP Concepts and Swing GUI Implementation

The document covers core Java OOP concepts such as static and final keywords, garbage collection, immutable classes, and polymorphism, alongside a shopping list manager implementation using Java Swing GUI. It details the design of an abstract Product class and its subclasses, StandardProduct and DiscountedProduct, demonstrating inheritance and polymorphism. The GUI design includes input fields, a JTable for displaying products, and functionality for adding products and calculating totals, ensuring a comprehensive understanding of Java OOP and GUI development.

Uploaded by

vqc288x06r
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)
25 views7 pages

Java OOP Concepts and Swing GUI Implementation

The document covers core Java OOP concepts such as static and final keywords, garbage collection, immutable classes, and polymorphism, alongside a shopping list manager implementation using Java Swing GUI. It details the design of an abstract Product class and its subclasses, StandardProduct and DiscountedProduct, demonstrating inheritance and polymorphism. The GUI design includes input fields, a JTable for displaying products, and functionality for adding products and calculating totals, ensuring a comprehensive understanding of Java OOP and GUI development.

Uploaded by

vqc288x06r
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

Java OOP Concepts and Swing GUI

Implementation
Question 1: Core Java Concepts
• Static keyword (fields/methods): The static modifier makes a field or method belong to the
class itself rather than any instance. Static fields/methods are shared by all instances and can be
accessed without creating an object 1 . For example, a static field is initialized once and shared, and
a static method can be called via ClassName.method() without an object 1 .
• Final keyword (fields/methods/classes): The final modifier prevents further modification or
inheritance. A final variable cannot be reassigned after initialization, making it a constant. A final
method cannot be overridden by subclasses, ensuring its implementation stays the same. A final class
cannot be subclassed at all, meaning no class can extend it 2 . These restrictions improve safety
and performance (the compiler may optimize final members knowing they won’t change) 2 .
• Garbage collection: In Java, garbage collection is an automatic memory management process done
by the JVM. The garbage collector periodically identifies objects that are no longer referenced
(unreachable) and reclaims their memory, so the programmer does not have to manually free
memory as in C/C++ 3 . This runs in the background and helps prevent memory leaks by deleting
“unused” objects and freeing heap space 3 .
• Immutable classes: An immutable class is a class whose instances cannot be modified after creation.
All fields of an immutable class are set once (typically via constructor) and have no setters, so the
object’s state never changes. A standard example is String : once a String object is created, its
value cannot change 4 . Immutable objects are thread-safe and can be safely shared or cached,
since their state remains constant 4 .
• Wrapper classes: A wrapper class is an object type that “wraps” a primitive type, allowing primitives
to be used where objects are required. For each primitive (e.g. int , double ), Java has a
corresponding wrapper class ( Integer , Double , etc.). Wrapper classes enable primitives to be
stored in collections like ArrayList (which only holds objects) and provide utility methods (e.g.
Integer.parseInt() ). For example:

Integer intObj = 5; // wraps primitive int 5


Double dblObj = 5.99; // wraps primitive double 5.99

As W3Schools notes: “Wrapper classes provide a way to use primitive data types ( int , boolean ,
etc.) as objects” 5 .
• Generalization: In OOP, generalization refers to identifying common features of multiple classes and
moving them into a more general superclass. It’s essentially creating a parent class for shared
attributes or behavior. For example, if DomesticFlight and InternationalFlight share
properties duration and capacity , we might generalize them into a common Flight
superclass. Subclasses then inherit from this general class. GeeksforGeeks describes it as “taking out
common properties and functionalities from two or more classes and combining them together into

1
another class which acts as the parent class” 6 . In other words, subclasses “are a type of” their
superclass (an “is-a” relationship) 6 .
• Upcasting and Downcasting: These are object type conversions in an inheritance hierarchy.
Upcasting is casting a subclass reference to its superclass type; it’s implicit and always safe (no
explicit cast needed). For example, if Child extends Parent , you can write Parent p = new
Child(); . The p reference can only see members defined in Parent . Downcasting is casting a
superclass reference back to a subclass type. This requires an explicit cast and may fail at runtime
with a ClassCastException if the object isn’t actually an instance of that subclass. For example:

Parent p = new Child(); // upcasting, implicit


Child c = (Child)p; // downcasting, explicit cast required

As GfG explains: “Upcasting is the typecasting of a child object to a parent object. Upcasting can be
done implicitly… Downcasting means the typecasting of a parent object to a child object” 7 .
• Why Java has no multiple inheritance (3 reasons): Java disallows a class from extending more than
one concrete class to avoid complexity and ambiguity. (1) Diamond Problem: If a class D extends
two classes B and C that both extend A , and B and C override a method from A , it’s unclear
which method D should inherit. Java avoids this ambiguity by allowing only single inheritance 8 .
(2) Simplicity of Design: Java’s designers prioritized a simpler, more maintainable class hierarchy.
Allowing only one superclass avoids conflicts (naming, state) and keeps the inheritance tree
straightforward 9 . (3) Maintenance and Clarity: Single inheritance ensures each class has one
clear lineage, making code easier to read and maintain. Java achieves multiple-type inheritance via
interfaces (which don’t carry concrete state/method implementations), so concrete classes stay
simple. In short, Java’s “design philosophy of simplicity and clarity over complexity” drives this choice
9 8 .

• Interfaces: An interface in Java is an abstract type that defines a contract of methods (and constants)
without providing their implementations (until Java 8 default methods). All methods in an interface
are implicitly public and abstract (before Java 8), and any class implementing the interface must
provide concrete implementations. Interfaces cannot be instantiated on their own. As W3Schools
puts it, “An interface is a completely ‘abstract class’ that is used to group related methods with empty
bodies” 10 . Interfaces allow multiple inheritance of type (a class can implement many interfaces),
enabling polymorphism and design flexibility 10 .
• Anonymous classes and anonymous objects: An anonymous class is a one-off class declared and
instantiated in a single expression, without a name. It is typically used to override or implement an
interface or extend a class for a single use. For example, Runnable r = new Runnable()
{ public void run() { /*...*/ } }; defines a Runnable on-the-fly. Anonymous classes
“enable you to declare and instantiate a class at the same time” and “do not have a name” 11 . An
anonymous object is simply an instance created without a reference variable. For example, new
Person("John", 30).display(); creates a Person object and immediately calls display()
on it without saving it to a variable. GeeksforGeeks defines an anonymous object as “an object that is
created without giving it a name” 12 . These are often used for single-use or one-line operations.

2
Question 2: Shopping List Manager Implementation

Part 1: OOP Design

1. Product (abstract class): We define an abstract class Product with the shared fields
productName ( String ), quantity ( int ), and unitPrice ( double ). It provides a
constructor to set these fields. Product declares an abstract method calculateTotalPrice()
and a concrete method getProductDetails() that returns a string of basic information (e.g.
"Name: ... Price: ... Quantity: ..." ). For example:

abstract class Product {


protected String productName;
protected int quantity;
protected double unitPrice;

public Product(String name, int quantity, double price) {


this.productName = name;
this.quantity = quantity;
this.unitPrice = price;
}
public String getProductDetails() {
return "Name: " + productName
+ ", Unit Price: " + unitPrice
+ ", Quantity: " + quantity;
}
public abstract double calculateTotalPrice();
}

Here, Product is a generalized superclass for all products. By abstracting common properties and
behaviors into Product , we follow the generalization (“is-a”) principle 6 .

2. StandardProduct subclass: StandardProduct extends Product and represents a regular item


with no discount. It inherits all fields and just provides an implementation of
calculateTotalPrice() , returning unitPrice * quantity . For example:

class StandardProduct extends Product {


public StandardProduct(String name, int quantity, double price) {
super(name, quantity, price);
}
@Override
public double calculateTotalPrice() {
return unitPrice * quantity;
}
}

3
3. DiscountedProduct subclass: DiscountedProduct also extends Product . It adds a field
discountPercentage ( double ). Its constructor initializes this extra field. Its
calculateTotalPrice() implementation first computes unitPrice * quantity and then
applies the discount percentage. For example:

class DiscountedProduct extends Product {


private double discountPercentage;
public DiscountedProduct(String name, int quantity, double price,
double discountPercent) {
super(name, quantity, price);
this.discountPercentage = discountPercent;
}
@Override
public double calculateTotalPrice() {
double subtotal = unitPrice * quantity;
double discountAmount = subtotal * (discountPercentage / 100.0);
return subtotal - discountAmount;
}
}

4. Polymorphism: By using the abstract Product type, the program can treat all products uniformly.
For example, we can store both StandardProduct and DiscountedProduct objects in a single
ArrayList<Product> . When we call calculateTotalPrice() on each Product , Java’s
runtime polymorphism invokes the correct subclass implementation. (This is analogous to a
Person p = new Father(); p.role(); example, where the overridden method in the subclass
executes 13 .) In our case, iterating through the list and summing
product.calculateTotalPrice() will correctly use each object’s overridden method.

Part 2: GUI Design and Functionality

1. Input Fields: The GUI (e.g. a JFrame or JPanel ) contains four text fields: one JTextField for
Product Name, one for Unit Price, one for Quantity, and one for Discount (%). For example:

JTextField nameField = new JTextField(20);


JTextField priceField = new JTextField(10);
JTextField quantityField = new JTextField(5);
JTextField discountField = new JTextField(5);

We could also add labels ( JLabel ) for clarity.

2. “Add to List” button: A JButton labeled “Add to List” is added. We attach an ActionListener that
triggers when the user clicks it. The listener’s code should:

3. Read the inputs from the text fields (using getText() and parsing numbers).

4
4. Decide which Product subclass to use: for example, if discountField is 0 or blank, create a
StandardProduct ; otherwise create a DiscountedProduct with that discount.
5. Create the Product instance and add it to an ArrayList<Product> shoppingList .
6. Update the JTable to show the new item row.
7. Recalculate and update the grand total display.

Example listener snippet:

addButton.addActionListener(e -> {
String name = nameField.getText();
double price = Double.parseDouble(priceField.getText());
int qty = Integer.parseInt(quantityField.getText());
double discount = Double.parseDouble(discountField.getText());
Product p;
if (discount > 0) {
p = new DiscountedProduct(name, qty, price, discount);
} else {
p = new StandardProduct(name, qty, price);
}
shoppingList.add(p);
// Update JTable model:
Object[] row = {
p.productName, p.unitPrice, p.quantity,
(p instanceof DiscountedProduct ? discount : "N/A"),
p.calculateTotalPrice()
};
tableModel.addRow(row);
// Update grand total:
calculateGrandTotal();
});

1. JTable display: We use a JTable to show the shopping list. Define column names and data model.
For example:

String[] columnNames = {"Product Name", "Unit Price", "Quantity",


"Discount (%)", "Total Price"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);

We then add the scroll pane to the frame. Each time a product is added, we call
tableModel.addRow(...) with that product’s details. This follows the standard Swing approach
where you supply column headings and data arrays to construct a table 14 . (In the Java tutorial
example, columns and data were given as arrays and passed to the JTable constructor 14 .) Here
we use DefaultTableModel so we can dynamically add rows.

5
2. Calculating Grand Total: Define a method (e.g. calculateGrandTotal() ) that iterates over the
shoppingList and sums each product’s total price:

double grandTotal = 0.0;


for (Product p : shoppingList) {
grandTotal += p.calculateTotalPrice();
}
totalLabel.setText("Grand Total: " + grandTotal);

We call this method after every addition or removal. This uses the polymorphic
calculateTotalPrice() on each item.

3. “Clear List” button (optional): An optional button labeled “Clear List” can clear the shopping list. Its
listener would do shoppingList.clear() , clear all rows from tableModel (e.g.
tableModel.setRowCount(0) ), and reset the grand total display to 0.

This design satisfies the requirements: inheritance (abstract Product and its subclasses), polymorphism
(using a common List<Product> and calling calculateTotalPrice() ), and a Swing GUI that reads
inputs, updates an ArrayList and JTable , and displays the grand total.

Sample Class Diagram (conceptual):

┌────────────┐
│ Product │◄──────── Generalization (inheritance)
│(abstract) │
│+name:String│
│+quantity:int│
│+unitPrice:double│
├────────────┤
│+getProductDetails()│
│+calculateTotalPrice():double (abstract)│
└────▲───┬────┘
│ │
┌───────┴───┴──────────┐
│ │
┌──────────────┐ ┌──────────────────┐
│ StandardProd │ │ DiscountedProduct│
│ (concrete) │ │ (concrete) │
├──────────────┤ ├──────────────────┤
│ │ │- discount:double │
├──────────────┤ ├──────────────────┤
│+calculateTotalPrice()│+calculateTotalPrice()│
└──────────────┘ └──────────────────┘

6
In this UML-like sketch, StandardProduct and DiscountedProduct each extend Product and
implement their own calculateTotalPrice() . The GUI code uses instances of these classes via the
Product reference type.

Sources: Definitions and descriptions of keywords and concepts were taken from authoritative Java tutorials
and references 1 2 3 4 5 6 7 9 8 10 12 11 14 , which illustrate these OOP and Swing
concepts.

1 static Keyword in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/static-keyword-java/

2 final Keyword in Java - GeeksforGeeks


https://www.geeksforgeeks.org/final-keyword-in-java/

3 Garbage Collection in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/garbage-collection-in-java/

4 How To Create an Immutable Class in Java | DigitalOcean


https://www.digitalocean.com/community/tutorials/how-to-create-immutable-class-in-java

5 Java Wrapper Classes


https://www.w3schools.com/java/java_wrapper_classes.asp

6 OOPS | Generalization as extension and restriction using Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/oops-generalization-as-extension-and-restriction-using-java/

7 Upcasting Vs Downcasting in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/upcasting-vs-downcasting-in-java/

8 9 Why Java doesn't support Multiple Inheritance? - GeeksforGeeks


https://www.geeksforgeeks.org/java/why-java-doesnt-support-multiple-inheritance/

10 Java Interface
https://www.w3schools.com/java/java_interface.asp

11 Anonymous Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

12 Anonymous Object in Java - GeeksforGeeks


https://www.geeksforgeeks.org/anonymous-object-in-java/

13 Polymorphism in Java - GeeksforGeeks


https://www.geeksforgeeks.org/java/polymorphism-in-java/

14 How to Use Tables (The Java™ Tutorials > Creating a GUI With Swing > Using Swing Components)
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html

You might also like