0% found this document useful (0 votes)
24 views19 pages

CSE215 Assignment

The document contains code for modeling geometric shapes as classes that extend an abstract GeometricObject class. GeometricObject defines common properties like color and methods like getArea(). Circle, Rectangle, and Triangle classes extend GeometricObject and implement shape-specific behavior like calculating areas and perimeters. A TestGeometricObject class displays two shapes and compares their areas to test the class hierarchy.

Uploaded by

Ahsanul Karim
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)
24 views19 pages

CSE215 Assignment

The document contains code for modeling geometric shapes as classes that extend an abstract GeometricObject class. GeometricObject defines common properties like color and methods like getArea(). Circle, Rectangle, and Triangle classes extend GeometricObject and implement shape-specific behavior like calculating areas and perimeters. A TestGeometricObject class displays two shapes and compares their areas to test the class hierarchy.

Uploaded by

Ahsanul Karim
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/ 19

1)

public class PopulationProjection {


public static void main(String[] args) {
long population = 172954319;

int birthsPerMinute = 1;
int deathsPerMinute = 2;
int netMigrantsPerMinute = 8;
int netMigrantsPerDay = 180;

for (int year = 1; year <= 5; year++) {


long births = birthsPerMinute * 60 * 24 * 365;
long deaths = deathsPerMinute * 60 * 24 * 365;
long netMigrants = netMigrantsPerDay * 365;

long populationChange = births - (deaths + netMigrants);

population += populationChange;

System.out.println("Year " + year + ": " + population);


}
}
}
Output:
2)
class MyString1 {
private String data;

public MyString1(String data) {


this.data = data;
}

public char charAt(int index) {


if (index >= 0 && index < data.length()) {
return data.charAt(index);
}
throw new IndexOutOfBoundsException("Index out of bounds");
}

public int length() {


return data.length();
}

public MyString1 substring(int begin, int end) {


if (begin >= 0 && end <= data.length() && begin <= end) {
return new MyString1(data.substring(begin, end));
}
throw new IndexOutOfBoundsException("Invalid substring indices");
}

public boolean equals(MyString1 s) {


return data.equals(s.toString());
}

public MyString1 toUpperCase() {


return new MyString1(data.toUpperCase());
}

@Override
public String toString() {
return data;
}
}

public class MyStringTest {


public static void main(String[] args) {
MyString1 nsuID = new MyString1("2233702642");

System.out.println("Length of the string is: " + nsuID.length());


System.out.println("Number at 8th digit is: " + nsuID.charAt(7));

MyString1 testString = new MyString1("Test123");


System.out.println("Is this string equal to 'Test123'? : " +
nsuID.equals(testString));

MyString1 last3Digits = nsuID.substring(nsuID.length() - 3, nsuID.length());


System.out.println("Last 3 digits of my NSU ID is: " + last3Digits);

MyString1 uppercaseID = nsuID.toUpperCase();


System.out.println("Uppercase of my string is: " + uppercaseID);

if (nsuID.charAt(7) == '6') {
System.out.println("8th digit of my NSU ID is 6. I must make it 0 before
graduating from NSU");
} else {
System.out.println("8th digit of my NSU ID is already 0.");
}
}
}

Output:
3)
class Time {
private int hour;
private int minute;
private int second;

public Time() {
long currentTimeMillis = System.currentTimeMillis();
setTime(currentTimeMillis);
}

public Time(long elapseTime) {


setTime(elapseTime);
}

public Time(int hour, int minute, int second) {


this.hour = hour;
this.minute = minute;
this.second = second;
}

public int getHour() {


return hour;
}

public int getMinute() {


return minute;
}

public int getSecond() {


return second;
}

public void setTime(long elapseTime) {


long totalSeconds = elapseTime / 1000;
second = (int) (totalSeconds % 60);
long totalMinutes = totalSeconds / 60;
minute = (int) (totalMinutes % 60);
long totalHours = totalMinutes / 60;
hour = (int) (totalHours % 24);
}
}

public class TestTime {


public static void main(String[] args) {
Time time1 = new Time();
Time time2 = new Time(555550000);
Time time3 = new Time(5, 23, 55);

System.out.printf("Time 1: %02d:%02d:%02d\n", time1.getHour(),


time1.getMinute(), time1.getSecond());
System.out.printf("Time 2: %02d:%02d:%02d\n", time2.getHour(),
time2.getMinute(), time2.getSecond());
System.out.printf("Time 3: %02d:%02d:%02d\n", time3.getHour(),
time3.getMinute(), time3.getSecond());
}
}

Output:
4)
(a) add(int y), display()

(b) add(int y), display()

(c) add(int y), The add method may not be overridden by any subclasses of
SuperClass because it is marked as final.

(d) Suppose there is another subclass of SuperClass called SubClass2; and a


further subclass of SubClass called NSU.
i) Draw an inheritance hierarchy of these 4 classes.

SuperClass
|
SubClass
|
SubClass2
|
NSU
ii) No, the statement NSU p = new SubClass() is not legal. This is because
NSU is a subclass of SubClass2, and SubClass2 is a subclass of SuperClass.
Therefore, an NSU object cannot be assigned to a SubClass variable.
iii) Yes, the statement NSU p = new SubClass2() is legal. This is because
NSU is a subclass of SubClass2, and a subclass can always be assigned to a
superclass variable.

(e) i) No, SuperClass is not an instance of SubClass. This is because SuperClass is


the parent class of SubClass.
ii) Yes, SubClass is an instance of SuperClass. This is because SubClass inherits
from SuperClass.
iii) No, SuperClass is not an instance of Subclass2. This is because SuperClass is
the parent class of Subclass2.
vi) No, SubClass2 is not an instance of SubClass. This is because SubClass2 is a
subclass of SubClass.
5)
Part#1:
● GeometricObject.java

public abstract class GeometricObject {


private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
// Construct a default geometric object
protected GeometricObject() {
dateCreated = new java.util.Date();
}
// Construct a geometric object with color and filled value
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
// Return color
public String getColor() {
return color;
}
// Set a new color
public void setColor(String color) {
this.color = color;
}
// Return filled. Since filled is boolean,
// the get method is named isFilled
public boolean isFilled() {
return filled;
}
// Set a new filled
public void setFilled(boolean filled) {
this.filled = filled;
}
// Get dateCreated
public java.util.Date getDateCreated() {
return dateCreated;
}
// Return a string representation of this object
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
// Abstract method getArea
public abstract double getArea();
// Abstract method getPerimeter
public abstract double getPerimeter();
}

● Circle.java

public class Circle extends GeometricObject {


private double radius;
public Circle() {
}
public Circle(double radius) {
this.radius = radius;
}
/** Return radius */
public double getRadius() {
return radius;
}
/** Set a new radius */
public void setRadius(double radius) {
this.radius = radius;
}
/** Return area */
public double getArea() {
return radius * radius * Math.PI;
}
/** Return diameter */
public double getDiameter() {
return 2 * radius;
}
/** Return perimeter */
public double getPerimeter() {
return 2 * radius * Math.PI;
}
/* Print the circle info */
public void printCircle() {
System.out.println("The circle is created " + getDateCreated() +
" and the radius is " + radius);
}
}

● Rectangle.java

public class Rectangle extends GeometricObject {


private double width;
private double height;
public Rectangle() {
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
/** Return width */
public double getWidth() {
return width;
}
/** Set a new width */
public void setWidth(double width) {
this.width = width;
}
/** Return height */
public double getHeight() {
return height;
}
/** Set a new height */
public void setHeight(double height) {
this.height = height;
}
/** Return area */
public double getArea() {
return width * height;
}
/** Return perimeter */
public double getPerimeter() {
return 2 * (width + height);
}
}

● Triangle.java

public class Triangle extends GeometricObject {


private double side1;
private double side2;
private double side3;

public Triangle(double side1, double side2, double side3) {


this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}

public double getSide1() {


return side1;
}

public double getSide2() {


return side2;
}

public double getSide3() {


return side3;
}

@Override
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

@Override
public double getPerimeter() {
return side1 + side2 + side3;
}

public boolean equalsArea(Triangle otherTriangle) {


return Math.abs(this.getArea() - otherTriangle.getArea()) < 0.0001;
}
}

● TestGeometricObject.java

public class TestGeometricObject {


/** Main method */
public static void main(String[] args) {
// Declare and initialize two geometric objects
GeometricObject geoObject1 = new Circle(3);
GeometricObject geoObject2 = new Rectangle(3, 4);
System.out.println("The two objects have the same area? " +
equalArea(geoObject1, geoObject2));
// Display circle
displayGeometricObject(geoObject1);
// Display rectangle
displayGeometricObject(geoObject2);

// Create Triangle object using Object class


Object object1 = new Circle(4);
Object object2 = new Rectangle(3, 4);
Object object3 = new Triangle(6, 8, 10);

System.out.println();
System.out.println("This is the result from the next case");
// Display circle, rectangle, and triangle
displayObject(object1);
displayObject(object2);
displayObject(object3);
}

/** A method for comparing the areas of two geometric objects */


public static boolean equalArea(GeometricObject object1, GeometricObject object2) {
return object1.getArea() == object2.getArea();
}

/** A method for displaying a geometric object */


public static void displayGeometricObject(GeometricObject object) {
System.out.println();
System.out.println("The area is " + object.getArea());
System.out.println("The perimeter is " + object.getPerimeter());
}

public static void displayObject(Object object) {


if (object instanceof Circle) {
System.out.println("The circle area is " +
((Circle) object).getArea());
System.out.println("The circle perimeter is " +
((Circle) object).getPerimeter());
} else if (object instanceof Rectangle) {
System.out.println("The rectangle area is " +
((Rectangle) object).getArea());
System.out.println("The rectangle perimeter is " +
((Rectangle) object).getPerimeter());
} else if (object instanceof Triangle) {
System.out.println("The triangle area is " +
((Triangle) object).getArea());
System.out.println("The triangle perimeter is " +
((Triangle) object).getPerimeter());
}
}
}
Output:
1. Encapsulation:

● Example: The private fields like radius in the Circle class and width and height in the
Rectangle class are encapsulated within their respective classes.

● Explanation: Encapsulation is achieved by using access modifiers (private) to hide


the internal state of objects. It helps in preventing unauthorized access and
modification of object properties.

2. Inheritance:

● Example: The Circle and Rectangle classes inherit from the GeometricObject class.

● Explanation: Inheritance allows the creation of new classes that are based on
existing classes, inheriting their attributes and behaviors. It promotes code reuse and
represents the "is-a" relationship between classes.

3. Polymorphism:

● Example: The equalArea method accepts different types of geometric objects as


arguments and compares their areas.

● Explanation: Polymorphism allows objects of different classes to be treated as


objects of a common superclass. The method can work with various types of
geometric objects, demonstrating the flexibility of OOP.

4. Abstraction:

● Example: The GeometricObject class defines abstract methods getArea and


getPerimeter.

● Explanation: Abstraction allows for the definition of common interfaces and abstract
methods without specifying their implementation details. It hides the complexity of the
implementation from the users of the class.
5. Class and Object:

● Example: The program defines classes such as GeometricObject, Circle, Rectangle,


and Triangle, and creates objects (instances) of these classes.

● Explanation: OOP revolves around the concept of classes and objects. Classes
define the blueprint for objects, and objects represent real-world entities. They
encapsulate data and behavior within a single unit.

6. Method Overloading:

● Example: The program includes two methods named equalArea with different
parameter lists (one for two objects and one for three objects).

● Explanation: Method overloading allows multiple methods with the same name but
different parameters to be defined within a class. It provides a way to create methods
that perform similar tasks but with different inputs.

7. Instanceof Operator:

● Example: The instanceof operator is used in the displayObject method to check the
type of an object.

● Explanation: The instanceof operator is used to determine whether an object is an


instance of a particular class. It is essential for making decisions based on the type of
an object at runtime.

These characteristics of OOP help in creating a well-structured and modular program that
models real-world entities effectively and promotes code organization, reusability, and
maintainability.

Part#2:
● MyGeometricObject

public abstract class MyGeometricObject {


private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
protected MyGeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with color and filled value */
protected MyGeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/** Return filled. Since filled is boolean,
* the get method is named isFilled */
public boolean isFilled() {
return filled;
}
/** Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}
/** Return a string representation of this object */
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
/** Abstract method getArea */
public abstract double getArea();
/** Abstract method getPerimeter */
public abstract double getPerimeter();
}

● MyRectangle

public class MyRectangle extends MyGeometricObject implements ExceptionInterface {


private double width;
private double height;
public MyRectangle() {
}

public MyRectangle(double width, double height) {


if (width < 0 || height < 0) {
throw new IllegalArgumentException("Width and height must be non-negative");
}
this.width = width;
this.height = height;
}

/** Return width */


public double getWidth() {
return width;
}

/** Set a new width */


public void setWidth(double width) throws IllegalArgumentException {
if (width < 0) throw new IllegalArgumentException("Width cannot be negative");
this.width = width;
}

/** Return height */


public double getHeight() {
return height;
}

/** Set a new height */


public void setHeight(double height) throws IllegalArgumentException {
if (height < 0) throw new IllegalArgumentException("Height cannot be negative");
this.height = height;
}

/** Return area */


public double getArea() {
return width * height;
}

/** Return perimeter */


public double getPerimeter() {
return 2 * (width + height);
}

// Implementation of setRadius is not necessary for rectangle but required by the interface.
// This can throw UnsupportedOperationException.
public void setRadius(double newRadius) {
throw new UnsupportedOperationException("Not applicable for rectangle");
}
}

● ExceptionInterface.java

import java.io.IOException;
public interface ExceptionInterface {
void setRadius(double newRadius) throws IllegalArgumentException;
}

● MyTestRectangle.java
public class MyTestRectangle {
public static void main(String[] args) {
MyGeometricObject rectangle1 = null;
MyGeometricObject rectangle2 = null;

try {
rectangle1 = new MyRectangle(-5, 10);
displayGeometricObject(rectangle1);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught for rectangle1: " + e.getMessage());
}

try {
rectangle2 = new MyRectangle(5, 10);
displayGeometricObject(rectangle2);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught for rectangle2: " + e.getMessage());
}
}

public static void displayGeometricObject(MyGeometricObject object) {


if (object != null) {
System.out.println();
System.out.println("The area is " + object.getArea());
System.out.println("The perimeter is " + object.getPerimeter());
} else {
System.out.println("No geometric object to display.");
}
}
}
Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy