0% found this document useful (0 votes)
15 views3 pages

Java Shape Class Examples

Java Code for abstraction

Uploaded by

tempmailfail
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)
15 views3 pages

Java Shape Class Examples

Java Code for abstraction

Uploaded by

tempmailfail
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

import [Link].

*;

abstract class Shape{


abstract double surfaceArea();
abstract double volume();
}

class Sphere extends Shape{


double r;

Sphere(double r){
this.r = r;
}

@Override
double surfaceArea(){
return 4 * [Link] * (r*r);
}
@Override
double volume(){
return (4/3)*[Link] * (r*r*r);
}
}

class Cube extends Shape{


double s;

Cube(double s){
this.s = s;
}

@Override
double surfaceArea(){
return 6 * (s * s);
}
@Override
double volume(){
return s*s*s;
}
}

class rectangularPrism extends Shape{


double l;
double w;
double h;

rectangularPrism(double l, double w, double h){


this.l = l;
this.w = w;
this.h = h;
}

@Override
double surfaceArea(){
return 2*(l*w+l*h+w*h);
}
@Override
double volume(){
return l*w*h;
}
}

class rightCircularCylinder extends Shape{


double r;
double h;

rightCircularCylinder(double r,double h){


this.r = r;
this.h = h;
}

@Override
double surfaceArea(){
return 2*([Link]*(r*r) + [Link]*r*h);
}
@Override
double volume(){
return [Link]*(r*r)*h;
}
}

public class Main{


public static void main(String[] arg){
Scanner sc = new Scanner([Link]);

//sphere
[Link]("Enter the values for Sphere : ");
[Link]("Enter the Radius: ");
double sphereR = [Link]();
Shape Sphere = new Sphere(sphereR);
[Link]("Sphere Surface Area = %.2f\n",[Link]());
[Link]("Sphere Volume = %.2f\n",[Link]());
[Link]();

//cube
[Link]("Enter the values for Cube : ");
[Link]("Enter the Side: ");
double cubeS = [Link]();
Shape Cube = new Cube(cubeS);
[Link]("Cube Surface Area = %.2f\n",[Link]());
[Link]("Cube Volume = %.2f\n",[Link]());
[Link]();

//Rectangular Prism
[Link]("Enter the values for Rectangular Prism : ");
[Link]("Enter the length: ");
double rectangularPrismL = [Link]();
[Link]("Enter the width: ");
double rectangularPrismW = [Link]();
[Link]("Enter the height: ");
double rectangularPrismH = [Link]();

Shape RectangularPrism = new


rectangularPrism(rectangularPrismL,rectangularPrismW,rectangularPrismH);
[Link]("Rectangular Prism Surface Area =
%.2f\n",[Link]());
[Link]("Rectangular Prism Volume =
%.2f\n",[Link]());
[Link]();

//Right Circular Cylinder


[Link]("Enter the values for Right Circular Cylinder : ");
[Link]("Enter the Radius: ");
[Link]("Enter the Height: ");
double rightCircularCylinderR = [Link]();
double rightCircularCylinderH = [Link]();
Shape RightCircularCylinder = new
rightCircularCylinder(rightCircularCylinderR,rightCircularCylinderH);
[Link]("Right Circular Cylinder Surface Area :
%.2f\n",[Link]());
[Link]("Right Circular Cylinder Volume :
%.2f\n",[Link]());
[Link]();

}
}

Common questions

Powered by AI

Polymorphism in the Java code lets a single interface (Shape) be used to refer to objects of any of its subclass types, allowing one to write more general and reusable code. It enhances flexibility by permitting interchangeable use of different shape objects without modifying application logic—the specific methods employed (surfaceArea and volume) are resolved at runtime based on the object type, not reference type. This supports robust application development, as it simplifies handling various shapes under a unified framework, and aids future expansion to include new shapes without altering existing code architecture significantly .

Encapsulation in OOP involves bundling the data (variables) and methods that operate on that data into a single unit or class, with controlled access through public methods. In the Java code, encapsulation is partially applied by defining private attributes (like radius, side, etc.) within classes, but improvements could be made by explicitly making these variables private and providing public getter methods. Setters could be omitted if immutability is preferable. This would enhance security, allowing control over how the shape properties are accessed and modified, thereby maintaining the integrity of the data within the classes .

The design of the shape classes enhances reusability and scalability by utilizing an abstract base class, Shape, which enforces a uniform interface for different types of shapes. The use of method overriding allows each shape class—Sphere, Cube, RectangularPrism, and RightCircularCylinder—to provide its own implementation for calculating surface area and volume. This approach not only simplifies the addition of new shapes (by extending the Shape class and implementing needed methods), but also ensures that all shape objects can be treated polymorphically, increasing the flexibility of the code base .

The current implementation generally adheres to the Single Responsibility Principle, each class has a single responsibility: to calculate the surface area and volume of a specific shape. By having distinct classes for each shape (Sphere, Cube, etc.), encapsulation of shape-specific logic is maintained. This makes extensions (adding more shapes) straightforward without affecting existing code, thus maintaining a clear separation of concerns. However, the overloading of computation (surface area and volume) within each class could be extracted into separate services if future logic became complex, thus adhering even more strictly to this principle as the system scales .

In the Java code, the surface area of a sphere is calculated using the formula 4 * π * r², and its volume is computed with (4/3) * π * r³. These formulas are based on geometric definitions: the surface area formula derives from integrating over the sphere's entire surface, modeling it as a continuous collection of infinitesimally small areas, while the volume formula results from the three-dimensional integration within the sphere's boundaries. In the code, these formulas work as intended because they are directly implemented in the respective methods, using Java’s built-in Math.PI for π .

The Java code takes user input using Scanner, which inherently poses issues such as runtime errors triggered by invalid inputs, like non-numeric values when expecting a double. This could lead to InputMismatchException if, for example, the user enters a string instead of a number. There’s also no validation to ensure the dimensions input are positive, which could lead to incorrect calculations of volume and surface area. These issues affect program stability by potentially causing crashes or erroneous results without clear feedback or exception handling mechanisms in place .

Refactoring the Java code to use interface segregation could lead to more modular and maintainable code. Interface Segregation Principle (ISP) suggests that no client should be forced to depend on methods it does not use. This means breaking down the monolithic Shape interface into smaller, more specific interfaces would allow concrete classes to implement only those methods that are relevant to them. For instance, if some shapes didn’t support volume, they wouldn’t need to implement a volume method. This change would facilitate adopting more focused and testable design, aiding in maintaining the system with minimal impact when changes are introduced .

Method overriding is crucial in the context of the shapes because it allows each subclass to provide a specific implementation for the surfaceArea and volume methods, tailored to its geometric properties. This achieves polymorphism, enabling a broader use of shape objects through a uniform interface. It makes code extensible and expandable, allowing new shapes to be introduced with their calculations without altering the existing code structure, maintaining the Open/Closed Principle of software design .

The Java code ensures type safety through its hierarchy of class designs by declaring an abstract class, Shape, which provides a blueprint for subclasses. Method signatures in Shape are abstract, necessitating concrete implementations in derived classes like Sphere, Cube, etc. This guarantees that any object instantiated from these subclasses will have a defined way of calculating surface area and volume, thereby maintaining type safety. Flexibility comes from the ability to instantiate different shapes using a single interface reference type (Shape), thus allowing polymorphic behavior that facilitates easy integration of new shape types without altering existing code structure .

In the given Java code, using an abstract class like Shape is effective because it allows the sharing of common characteristics across its subclasses, ensures that method definitions like surfaceArea and volume must be implemented, and provides a clear defined hierarchy. Abstract classes can contain implemented methods and state (fields), which might be useful if there were shared fields or behaviors. However, interfaces could offer more flexibility, especially if Java 8’s default methods are utilized. Interfaces support multiple inheritance, which could be beneficial if a shape should incorporate traits from multiple sources. The choice between abstract classes and interfaces depends on whether shared state or behavior needs to be encapsulated at the abstract level .

You might also like