Saturday, August 19, 2023

Program in java having its all features

Creating a Java program that showcases all of its features would be quite extensive, as Java is a versatile programming language with numerous features. However, I can provide you with a simple example that demonstrates some of Java's fundamental features. Let's create a program that defines a class, uses inheritance, interfaces, exceptions, and basic I/O:

import java.io.*; import java.util.*; // Define an interface interface Shape { double calculateArea(); } // Create a class implementing the interface class Circle implements Shape { private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } } // Create another class extending the Circle class class Cylinder extends Circle { private double height; public Cylinder(double radius, double height) { super(radius); this.height = height; } public double calculateVolume() { return calculateArea() * height; } } // Demonstrate exception handling class NegativeValueException extends Exception { public NegativeValueException(String message) { super(message); } } // Main class public class JavaFeatureDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the radius of the circle: "); double circleRadius = scanner.nextDouble(); try { if (circleRadius < 0) { throw new NegativeValueException("Radius cannot be negative"); } Circle circle = new Circle(circleRadius); System.out.println("Area of the circle: " + circle.calculateArea()); System.out.print("Enter the height of the cylinder: "); double cylinderHeight = scanner.nextDouble(); if (cylinderHeight < 0) { throw new NegativeValueException("Height cannot be negative"); } Cylinder cylinder = new Cylinder(circleRadius, cylinderHeight); System.out.println("Volume of the cylinder: " + cylinder.calculateVolume()); } catch (NegativeValueException e) { System.out.println("Error: " + e.getMessage()); } } }


This program demonstrates the following Java features:

  1. Class and object creation
  2. Inheritance (Cylinder extending Circle)
  3. Interface (Shape)
  4. Exception handling (NegativeValueException)
  5. Basic I/O using Scanner and System.out
  6. Method overriding (calculateArea() in Circle and calculateVolume() in Cylinder)

No comments:

Post a Comment

If you have any Doubts then please let me know