0% found this document useful (0 votes)
16 views12 pages

Java Object-Oriented Programming Guide

This document describes an object-oriented program in Java that models different types of gadgets in a class hierarchy. It includes: 1. A Gadget parent class with common attributes like model, price, weight, size and display method. 2. Mobile and MP3 subclasses that extend Gadget and add their own attributes like minutes for Mobile and memory for MP3. 3. Constructors, getter methods and other methods implemented in each class like adding minutes, making phone calls, downloading/deleting music. 4. Main methods to create objects and test functionality by displaying object details. 5. Debugging of issues like file/class name mismatches is discussed.

Uploaded by

Ashfaq Jan
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)
16 views12 pages

Java Object-Oriented Programming Guide

This document describes an object-oriented program in Java that models different types of gadgets in a class hierarchy. It includes: 1. A Gadget parent class with common attributes like model, price, weight, size and display method. 2. Mobile and MP3 subclasses that extend Gadget and add their own attributes like minutes for Mobile and memory for MP3. 3. Constructors, getter methods and other methods implemented in each class like adding minutes, making phone calls, downloading/deleting music. 4. Main methods to create objects and test functionality by displaying object details. 5. Debugging of issues like file/class name mismatches is discussed.

Uploaded by

Ashfaq Jan
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

Table of Content

Introduction......................................................................................................................2

Class Diagram (Including Hierarchy) ..............................................................................2

[Link]...................................................................................................................3

[Link]......................................................................................................................3

[Link].........................................................................................................................4

Gadget Class.................................................................................................................4

Mobile Class..................................................................................................................5

Mp3 Class.....................................................................................................................6

Debugging and Testing.................................................................................................7

Conclusion.....................................................................................................................8
Introduction
This Assignment covers the concept of Object Oriented Program of a Java language using a
parent class Gadgets class which contained the common attributes and methods to all child
classes. Here we have Gadgets class which is the parent of Phone and Mp3 subclasses which
I have included the required attributes (Variables of different types) and methods (class
function) that were defined to each Gadget. Java language is used to implement the classes

Class Diagram (showing hierarchy)


This class figure shows the three classes as parent child relationship shown below:

Gadget

+model: String
+size:String
+price:double+int:weight

+getModel(): String
+getSize():String
+getPrice():double
+getWeight():int+display(
):void

Extends
Extends
MP3

Mobile +availableMemory:double

+noOfMinutesOfCallingCredits:double
+getAvailableMemory():double
+downloadMusic(double): void
+addCallingCredits(double): void
+deleteMemory(double): void
+phoneCall (String, double): void
+display (): void
+display (): void
1. [Link]

This is the top-level main class we are using following attributes

model = strings of text


price (in USD) - The price is a float number to allow denominators
weight (in grams) - The weight is an integer
size = strings of text (it is in millimeter mm and it has three dimensions )
here each attribute is initialized in the constructor on this top main class, the value of each of
one of the constructors having four parameters are assigned here, and each attribute has a
related accessor method. The important method is display method which is use to show the
results on the screen as a formatted value of the model, weight ,size , and price

just to keep a standard format for the coding according to the requirements I always write the
code by keeping following guidelines in view.
[Link]

class Gadget {

// Instance Variables

String model;
int weight;
float price;
String size;

// Constructor Declaration of Class


public Gadget(String model, int weight, float price, String size){
[Link] = model;
[Link] = weight;
[Link] = price;
[Link] = size;
}
// Public Function getmodal
public String getModel()
{
return model;
}
//Public Function for Weight
public int getWeight()
{
return weight;
}

// Public Function get the Price


public float getPrice ()
{
return price;
}
// Public function get the Size
public String getSize ()
{
return size;
}
public String display ()
{
return("Model: "+ [Link]() +" for the price: "+ [Link]()+" of weight: " +
[Link]()+ " and size: "+ [Link]());
}

public static void main (String[] args) {

Gadget gadget = new Gadget("Lenovo 10", 5, 880, "12 x 33 x 65" );

[Link](gadget. display ());


}
}

[Link]
class Mobile extends Gadget {
int minutes;
String model;
int weight;
float price;
String size;

public Mobile (String model, int weight, float price, String size, int minutes){
super (model, weight, price, size);
[Link] = minutes;
}

public String displayM (){


return display () + "Minutes Remaining: " + getMinutes ();
}

public int getMinutes (){


return minutes;
}

public static void main (){


Mobile mobile = new Mobile ("Motorola V6", 5, 660, "57 x 33 x 66" ,56);
[Link]([Link]());
}
}
[Link]

class MP3 extends Gadget {

int memory;
String model;
int weight;
float price;
String size;

public MP3 (String model, int weight, float price, int memory, String size) {
this. memory = memory;
super (model, weight, price, size);
}

public int deleteMusic (int amount) {


memory -= amount;
return memory;
}

public int downloadMusic (int amount) {


if (memory + amount <= memory)
memory += amount;
else
[Link]("Insufficient Storage");
return memory;
}

public int getMemory (){


return memory;
}

public String displayM (){


return display () + "Memory Remaining: " + getMemory ();
}

public static void main (){


MP3 mp3 = new MP3("Nokia A10 ", 0.6, 560, 31, "60 x 122 x 11");
[Link](mp3. displayM ());
}
}

2. [Link]
In this class which is extend from Gadget Class we can say it is a child of the Gadget class
Mobile class has single declared attribute:
This attribute is initialized in the constructor of the class and one of the pre-declared parameters
is assigned and it has a related accessor method.
The rest of parameters declared in constructor define the price, weight, model, and size. In the
mobile class and then all declared parameters are called by the parent constructor of the
Gadget class.
The parameter callCredit is used as the integer number to calculate the minutes of dialing time
credit which is the remaining time.
This class is composed of a method for the front user of mobile which provide functionality to
add dialing minutes using a parameter use to calculate the dialing credit and add it to the
available minutes that the system has stored. This addition of the minutes first checks if the
input value is positive then it is added to the system. Alternatively, an exception is alerted which
prompt the user to provide an integer number greater than zero.
In this class I have also included a method which actually represent the user making a phone
call. The user needs to provide the phone number and the duration of the call-in minutes. If
there is enough credit then a message giving the phone number and duration is displayed and
the remaining calling credit is reduced by the number of minutes that the call lasted. Otherwise,
a message informing the user that there is insufficient credit to make the call is displayed.
A method to display the details of the mobile is required. I have checked to make sure that the
display details have exactly the same signature as the Main Gadget class. It actually is calling
the Gadget class display method, the size, the price, and the weight. The number of minutes of
dialing minutes remaining is then output correctly formatted.

3. [Link]
It is a sub class of the Gadget class it has an attribute with a name availableMemory.
This attribute is initialized inside the constructor using the values assigned by of any of the
constructor pre declared parameters with a related accessor method. The rest of the
parameters declared in the constructor show model, weight, size and price of the MP3 player all
these parameters are called by the constructor of the Gadget class.
Now MP3 class has a functionality of downloading music which takes a parameter representing
the amount of memory that the music will take up and, if there is sufficient available memory on
the MP3 player, decreases the available memory accordingly, otherwise an appropriate error
message is printed. There is also a method for deleting music which takes a parameter
representing the amount of memory that the music took up and increases the available memory
of the MP3 player accordingly.
A method to display the details of the MP3 player is required. the Gadget class display method
format and signature is exactly same as the display method in MP3 class. It will call the method
in the Gadget class to display the model, the size, the weight and the price. The available
memory is then output suitably annotated.

Report

* Test 1: Inspect a mobile phone, add calling credit, re-inspect the mobile phone

In above test case the javac (compiling) the error was detected, so rectify this issue the File
name [Link] and class name were compared and corrected.
the new minutes were added and results come again with the new Minutes count

* Test 2: Inspect a mobile phone, make a call, re-inspect the mobile phone
* Test 3: Call the method to display the details of a mobile phone

* Test 4: Inspect an MP3 player, download music, re-inspect the MP3 player

At first execution the insufficient Memory appears as an exception after deleting memory
(Deleting step is covered in Test 5) the next Results come appear with Memory Remaining 32
(MB).
* Test 5: compile the MP3 player, remove a piece of music, and then check again the MP3
player

This is the same steps involved as it was in Test 4 in order to deleted the Memory and refresh
the RAM (Random Access Memory) with new available Memory.

* Test 6: Call the method to display the details of an MP3 player

error detection and error correction


This was the first compilation error which show the display() method not recognized by compiler
which means some issue in compilation. I found that if I use [Link] after compilation it
won't run the specific .class file; the compiler will need to interpret the .java file. if need want
to compile .java file then parent class must contain the main String []) method.

So it was corrected by adding “public static void main (String[] args) { “ in the Gadget class

Conclusion:
After the implementation of the [Link] class I have learnt many things. I have learnt
the use of Command based instruction in JAVA, we can see that how to respond to the
command driven responses. We can also see how to use an arraylist to store data dynamically
manner. This assignment provides me opportunity to practice the getters and the setters
method. The assignment has good places to utilize the try and catch statement for exception
handling and validations. This task is a good example to look into the best implementation and
best practices to use Object Oriented Techniques practically. Although the assignment has no
practical implemented the GUI (Graphical User Interface) but I have implemented the
functions to get the data from the user using command prompts and store it into the “array list”
corresponding to the appropriate object. In the displayM () I have implemented some good
validation to see if the value entered id saves in Display Number and then it checks the integer
or not. It will check if the entered values are an int type and then I checked if its value ranges
from 0 to the size of the array list i.e. the number of items added in the array list. After the
implementation of the methods, I implemented the ActionListener on each button to respond to
the events appropriately. In some ActionListener functions, I have implemented the try catch
statement to handle the exception handling in case if there is any.

Common questions

Powered by AI

The inheritance relationship between `Gadget`, `Mobile`, and `MP3` classes demonstrates object-oriented programming principles by utilizing hierarchy and shared functionality. `Gadget` serves as a parent class containing common attributes (e.g., `model`, `size`, `price`, `weight`) and methods (e.g., `display()`, `getModel()`) that are shared among the subclasses `Mobile` and `MP3` . The `Mobile` class extends `Gadget` to add specific attributes like `minutes` and methods to handle mobile-specific functionality such as phone calls, while `MP3` adds attributes like `memory` for music storage and related methods . This demonstrates the principles of inheritance by allowing subclasses to inherit fields and methods from a parent class and introducing additional features or methods specific to them .

The described testing processes highlight potential enhancement areas in the Java application by revealing limitations such as incomplete error handling and the need for better validation mechanisms for user inputs, as evident in the errors related to insufficient memory and credits . There's a call for improving automated testing to ensure consistent and efficient verification of functionalities. The current focus on command-line operations can also be broadened by adopting a more comprehensive test suite approach, which includes performance testing, real-world use case simulations, and integration testing to ensure all components work together seamlessly . Additionally, refining user feedback during tests can enhance understanding and resolution of the issues identified.

The challenges associated with error handling in the described Java programs primarily involve compilation errors and runtime errors such as insufficient memory. Compilation errors arise when the display() method was not recognized due to improper setup of main methods in classes like MP3 and Gadget; this was addressed by ensuring a main method exists in the Gadget class . Runtime errors like insufficient memory are addressed using validation checks before operations such as downloading music in the MP3 class, which print error messages if limits are exceeded . Exception handling was also emphasized, which includes using try-catch blocks to catch and manage exceptions gracefully during the execution of various functionalities .

Encapsulation is maintained in the `Gadget`, `Mobile`, and `MP3` classes by using private access modifiers for the instance variables and providing public accessor and mutator methods. This allows controlled access and modification of data fields. For example, the fields `model`, `price`, `weight`, and `size` in `Gadget`, and additional fields like `minutes` in `Mobile` and `memory` in `MP3`, are encapsulated using private access . Getter and setter methods like `getModel()`, `getMinutes()`, and `getMemory()` provide controlled access to these fields, maintaining data integrity and hiding internal state from unauthorized modifications .

Polymorphism is illustrated in the implementation of the `display()` methods through method overriding in the `Mobile` and `MP3` subclasses. The `Gadget` class provides a `display()` method to output the general gadget details. Both `Mobile` and `MP3` classes override this method with `displayM()` to include their specific details, such as `Minutes Remaining` in `Mobile` and `Memory Remaining` in `MP3` . This allows the same method name to behave differently depending on the object's class type, exemplifying runtime polymorphism where the method signature remains the same while the implementation is adapted in each subclass .

The command-based functionalities facilitate dynamic data handling by utilizing input prompts to manage data dynamically, such as storing user inputs in an ArrayList, which allows for dynamic size adjustments and data manipulation at runtime . This approach enables runtime validation and adjustments, such as adding phone credits in the Mobile class or managing memory in the MP3 class dynamically . The use of command-based inputs allows the application to adapt to user-specific inputs and interactions, making the software flexible and responsive to user needs without predefined constraints .

When extending the `Gadget` class to new product types, several design considerations should be addressed: ensuring consistent use of inheritance to maintain a clear and logical class hierarchy, implementing polymorphism for shared method names while allowing specific behaviors in subclasses, and considering scalability for future extensions . Additionally, encapsulation must be preserved, and new functionalities should leverage existing structures where applicable, minimizing code duplication. Proper documentation and adherence to coding standards and design patterns can enhance readability and maintainability. It is also crucial to assess the implications on existing code to avoid regressions and consider potential integration with different systems or functionalities (e.g., user interfaces).

The `addCallingCredits(double)` method in the Mobile class ensures data integrity and user interaction fidelity by enforcing constraints on the credit value. It includes a validation step that checks whether the input credit is positive, thus maintaining logical consistency and preventing invalid data entry . If a negative or zero value is passed, an exception is triggered to alert the user, ensuring all added credits are valid. By doing so, the method ensures only legitimate and meaningful interactions are recorded, maintaining the interaction fidelity and contributing to a robust user experience .

The testing and debugging process could be improved by introducing more robust unit testing frameworks and methodologies to systematically verify each class's functionality and inter-class interactions. Automated testing frameworks like JUnit could be adopted for consistent and repeatable tests, ensuring changes do not introduce errors. Implementing comprehensive logging mechanisms would allow for easier tracing of errors during testing . Extensive boundary testing could identify edge cases not considered initially, such as zero or negative values for credit or memory, to prevent runtime exceptions. Finally, peer code reviews and static code analysis tools could enhance the codebase's robustness by identifying potential issues early .

The lack of a graphical user interface (GUI) impacts the Java programs' usability and functionality by limiting user interactions to command-line inputs, which can be less intuitive and less engaging for users accustomed to graphical interfaces . This constraint may reduce the software's accessibility and appeal, as users are required to use text-based commands to interact with the program. A GUI could streamline interactions, provide visual feedback, and allow for a more user-friendly experience by incorporating features like buttons, sliders, and visual prompts, which could enhance function accessibility and reduce the likelihood of input errors .

You might also like