0% found this document useful (0 votes)
13 views

Lab 8

The document discusses two programming tasks for a lab on polymorphism. Task 1 involves creating abstract and concrete classes for living things like humans and monkeys. Task 2 involves modeling an online shop using abstract product classes and concrete subclasses for different product types like books, TVs and MP3 players.

Uploaded by

Niaz Khan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lab 8

The document discusses two programming tasks for a lab on polymorphism. Task 1 involves creating abstract and concrete classes for living things like humans and monkeys. Task 2 involves modeling an online shop using abstract product classes and concrete subclasses for different product types like books, TVs and MP3 players.

Uploaded by

Niaz Khan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Department of Computing

CS 212: Object Oriented Programming

Lab 08: Polymorphism


CLO2 -Evaluate complex programming problems using object-oriented principles analyzing
solutions for efficiency and scalability.

CLO3 -Build programs using the latest IDEs as per standard practices applicable to the
software industry.

CLO4 – Develop solutions to real world problems by applying appropriate object-oriented


techniques.

Date: 15-04-2024

Time: 2:00pm- 5:00 pm


Name: Muhammad Hassaan Noor

CMS: 470174

Instructor: Dr Rehan Ahmad


Lab Engineer: Engr. Masabah Bint E Islam

CS 212: Object Oriented Programming Page 1


Lab Tasks

Reference Book: Java How to Program, 10th Ed, Deitel & Deitel (Available on LMS)

Task# 1:

Write an abstract class LivingThing.java followed by two concrete classes, Human.java and
Monkey.java, extending the abstract class.

Once done defining classes use the following client class to test it.

package myabstractclassproject;

public class Main {


public static void main( String[] args) {
// Create Human object instance
// and assign it to Human type.
Human human1 = new Human( "Will Rodman");
human1.walk();
CS 212: Object Oriented Programming Page 2
// Create Human object instance
// and assign it to LivingThing type.
LivingThing livingthing1 = human1;
Running the test should result in the following output.

Human Will Rodman walks...


Human Will Rodman walks...
Monkey Caesar also walks...
human1.getName() = Will Rodman
livingthing1.getName() = Will Rodman
Do human1 and livingthing1 point to the same object instance? true

Bonus. What happens when you create a LivingThing object in the Main class? For example
using the statement,
LivingThing z = new LivingThing();

Code:

//Written by Muhammad Hassaan Noor - 470174

package Lab8;

abstract class LivingThing


{

private String name;

public LivingThing(String name) {


this.name=name;
}

public void breath(){

public void eat(){

public abstract void walk();

CS 212: Object Oriented Programming Page 3


public String getName(){
return this.name;
}

public void setName(String name){


this.name=name;
}

class Human extends LivingThing{

public Human(String name) {


super(name);
}

@Override
public void walk() {
System.out.println("Human " + this.getName() + " walks...");
}
}

class Monkey extends LivingThing{

public Monkey(String name) {


super(name);
}

@Override
public void walk() {
System.out.println("Monkey " + this.getName() + " walks...");
}
}

public class Main {


public static void main( String[] args) {
// Create Human object instance
// and assign it to Human type.
Human human1 = new Human( "Will Rodman");
human1.walk();

// Create Human object instance


// and assign it to LivingThing type.
LivingThing livingthing1 = human1;
livingthing1.walk();

// Create a Monkey object instance


// and assign it to LivingThing type.
LivingThing livingthing2 = new Monkey( "Caesar");
livingthing2.walk();

// Display data from human1 and livingthing1.

CS 212: Object Oriented Programming Page 4


// Observe that they refer to the same object instance.
System.out.println( "human1.getName() = " + human1.getName());
System.out.println( "livingthing1.getName() = " +
livingthing1.getName());

// Check of object instance that is referred by x and


// y is the same object instance.
boolean b1 = ( human1 == livingthing1);
System.out.println( "Do human1 and livingthing1 point to the same
object instance? " + b1);
}
}

Output:

Bonus:

Instance of Abstract Class cant be created.

Task# 2:

Your task is to write MyOnlineShop program by referring to the UML class diagram below.

CS 212: Object Oriented Programming Page 5


Once done with the class definitions use the following tester class to confirm its working.

package myonlineshop;

public class Main {

public static void main(String[] args) {

// Declare and create Product array of size 5

Product[] pa = new Product[5];

// Create object instances and assign them to

// the type of Product.

CS 212: Object Oriented Programming Page 6


pa[0] = new TV( 1000, "Samsung", 30);

pa[1] = new TV( 2000, "Sony", 50);

pa[2] = new MP3Player( 250, "Apple", "blue");

pa[3] = new Book( 34, "Sun press", 1992);

pa[4] = new Book( 15, "Korea press", 1986);

// Compute total regular price and total

// sale price.

double totalRegularPrice = 0;

double totalSalePrice = 0;

for (int i=0; i<pa.length; i++){

// Call a method of the super class to get

// the regular price.

totalRegularPrice += pa[i].getRegularPrice();

// Since the sale price is computed differently

// depending on the product type, overriding (implementation)

// method of the object instance of the sub-class

// gets invoked. This is runtime polymorphic

// behavior.

totalSalePrice += pa[i].computeSalePrice();

CS 212: Object Oriented Programming Page 7


System.out.println("Item number " + i +

": Type = " + pa[i].getClass().getName() +

", Regular price = " + pa[i].getRegularPrice() +

", Sale price = " + pa[i].computeSalePrice());

System.out.println("totalRegularPrice = " + totalRegularPrice);

System.out.println("totalSalePrice = " + totalSalePrice);

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
totalRegularPrice = 3299.0
totalSalePrice = 2649.5

Code:

//Written by Muhammad Hassaan Noor - 470174

package myonlineshop;

abstract class Product{

private double regularPrice;

CS 212: Object Oriented Programming Page 8


public Product(double regualarPrice) {
this.regularPrice = regualarPrice;
}

public double getRegularPrice() {


return regularPrice;
}

public void setRegularPrice(double regualarPrice) {


this.regularPrice = regualarPrice;
}

public abstract double computeSalePrice();

class Book extends Product{


@Override
public double computeSalePrice() {
return this.getRegularPrice()-(0.50*this.getRegularPrice());
}

public Book(double regualarPrice, String publisher, int yearPublished) {


super(regualarPrice);
this.publisher=publisher;
this.yearPublished=yearPublished;
}

private String publisher;


private int yearPublished;

public String getPublisher() {


return publisher;
}

public void setPublisher(String publisher) {


this.publisher = publisher;
}

public int getYearPublished() {


return yearPublished;
}

public void setYearPublished(int yearPublished) {


this.yearPublished = yearPublished;
}
}

abstract class Electronics extends Product{

private String manfacturer;

CS 212: Object Oriented Programming Page 9


public String getManfacturer() {
return manfacturer;
}

public void setManfacturer(String manfacturer) {


this.manfacturer = manfacturer;
}

public Electronics(double regualarPrice, String manfacturer) {


super(regualarPrice);
this.manfacturer = manfacturer;
}
}

class MP3Player extends Electronics{

@Override
public double computeSalePrice() {
return this.getRegularPrice()-(0.10*this.getRegularPrice());
}

private String color;

public MP3Player(double regualarPrice, String manfacturer, String color) {


super(regualarPrice, manfacturer);
this.color = color;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}
}

class TV extends Electronics{

private int size;

public TV(double regualarPrice, String manfacturer, int size) {


super(regualarPrice, manfacturer);
this.size = size;
}

@Override
public double computeSalePrice() {
return this.getRegularPrice()-(0.20*this.getRegularPrice());
}
}

CS 212: Object Oriented Programming Page 10


public class Main {

public static void main(String[] args) {

// Declare and create Product array of size 5


Product[] pa = new Product[5];

// Create object instances and assign them to


// the type of Product.
pa[0] = new TV( 1000, "Samsung", 30);
pa[1] = new TV( 2000, "Sony", 50);
pa[2] = new MP3Player( 250, "Apple", "blue");
pa[3] = new Book( 34, "Sun press", 1992);
pa[4] = new Book( 15, "Korea press", 1986);

// Compute total regular price and total


// sale price.
double totalRegularPrice = 0;
double totalSalePrice = 0;

for (int i=0; i<pa.length; i++){

// Call a method of the super class to get


// the regular price.
totalRegularPrice += pa[i].getRegularPrice();

// Since the sale price is computed differently


// depending on the product type, overriding (implementation)
// method of the object instance of the sub-class
// gets invoked. This is runtime polymorphic
// behavior.
totalSalePrice += pa[i].computeSalePrice();

System.out.println("Item number " + i +


": Type = " + pa[i].getClass().getName() +
", Regular price = " + pa[i].getRegularPrice() +
", Sale price = " + pa[i].computeSalePrice());
}

System.out.println("totalRegularPrice = " + totalRegularPrice);


System.out.println("totalSalePrice = " + totalSalePrice);
}
}

Output:

CS 212: Object Oriented Programming Page 11


Task# 3:

Modify the MyLine, MyOval and MyRectangle classes of GUI and Graphics Case Study
Exercise 8.1 and Exercise 9.1 of the reference book to create the class hierarchy in the below
Figure. Classes of the MyShape hierarchy should be “smart” shape classes that know how to
draw themselves (if provided with a Graphics object that tells them where to draw). Once the
program creates an object from this hierarchy, it can manipulate it polymorphically for the
rest of its lifetime as a MyShape.

In your solution, class MyShape must be abstract. Since MyShape represents any shape in
general, you cannot implement a draw method without knowing specifically what shape it is. The
data representing the coordinates and color of the shapes in the hierarchy should be declared as
private members of class MyShape. In addition to the common data, class MyShape should
declare the following methods:

a) A no-argument constructor that sets all the coordinates of the shape to 0 and the color to
Color.BLACK.
b) A constructor that initializes the coordinates and color to the values of the arguments
supplied.
c) Set methods for the individual coordinates and color that allow the programmer to set any
piece of data independently for a shape in the hierarchy.
d) Get methods for the individual coordinates and color that allow the programmer to
retrieve any piece of data independently for a shape in the hierarchy.
e) The abstract method

CS 212: Object Oriented Programming Page 12


public abstract void draw(Graphics g);

which the program’s paintComponent method will call to draw a shape on the screen.
To ensure proper encapsulation, all data in class MyShape must be private. This requires
declaring proper set and get methods to manipulate the data. Class MyLine should provide a no-
argument constructor and a constructor with arguments for the coordinates and color. Classes
MyOval and MyRectangle should provide a no-argument constructor and a constructor with
arguments for the coordinates, color and determining whether the shape is filled. The no-
argument constructor should, in addition to setting the default values, set the shape to be an
unfilled shape.

You can draw lines, rectangles and ovals if you know two points in space. Lines require x1, y1,
x2 and y2 coordinates. The drawLine method of the Graphics class will connect the two points
supplied with a line. If you have the same four coordinate values (x1, y1, x2 and y2) for ovals and
rectangles, you can calculate the four arguments needed to draw them. Each requires an upper-
left x-coordinate value (the smaller of the two x-coordinate values), an upper-left y-coordinate
value (the smaller of the two y-coordinate values), a width (the absolute value of the difference
between the two x-coordinate values) and a height (the absolute value of the difference between

CS 212: Object Oriented Programming Page 13


the two y-coordinate values). Rectangles and ovals should also have a filled flag that determines
whether to draw the shape as a filled shape.

There should be no MyLine, MyOval or MyRectangle variables in the program—only


MyShape variables that contain references to MyLine, MyOval and MyRectangle objects.
The program should generate random shapes and store them in an array of type MyShape.
Method paintComponent should walk through the MyShape array and draw every shape, by
polymorphically calling every shape’s draw method.

Allow the user to specify (via an input dialog) the number of shapes to generate. The program
will then generate and display the shapes along with a status bar that informs the user how many
of each shape were created.

Code:

package Task3;

import java.awt.*;
import javax.swing.*;

abstract class MyShape {


private double x1, y1, x2, y2;
private Color color;

public MyShape() {
this(0, 0, 0, 0, Color.BLACK);
}

public MyShape(double x1, double y1, double x2, double y2, Color color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}

public double getX1() {


return x1;
}

public void setX1(double x1) {

CS 212: Object Oriented Programming Page 14


this.x1 = x1;
}

public double getY1() {


return y1;
}

public void setY1(double y1) {


this.y1 = y1;
}

public double getX2() {


return x2;
}

public void setX2(double x2) {


this.x2 = x2;
}

public double getY2() {


return y2;
}

public void setY2(double y2) {


this.y2 = y2;
}

public Color getColor() {


return color;
}

public void setColor(Color color) {


this.color = color;
}

public abstract void draw(Graphics g);


}

class MyLine extends MyShape {


public MyLine() {
}

public MyLine(double x1, double y1, double x2, double y2, Color color) {
super(x1, y1, x2, y2, color);
}

@Override
public void draw(Graphics g) {
g.setColor(getColor());
g.drawLine((int) getX1(), (int) getY1(), (int) getX2(), (int)
getY2());
}
}

CS 212: Object Oriented Programming Page 15


class MyOval extends MyShape {
private boolean filled;

public MyOval() {
super(0, 0, 50, 50, Color.RED);
this.filled = false;
}

public MyOval(double x1, double y1, double x2, double y2, Color color,
boolean filled) {
super(x1, y1, x2, y2, color);
this.filled = filled;
}

public boolean isFilled() {


return filled;
}

public void setFilled(boolean filled) {


this.filled = filled;
}

@Override
public void draw(Graphics g) {
g.setColor(getColor());
if (filled)
g.fillOval((int) Math.min(getX1(), getX2()), (int)
Math.min(getY1(), getY2()),
(int) Math.abs(getX2() - getX1()), (int) Math.abs(getY2()
- getY1()));
else
g.drawOval((int) Math.min(getX1(), getX2()), (int)
Math.min(getY1(), getY2()),
(int) Math.abs(getX2() - getX1()), (int) Math.abs(getY2()
- getY1()));
}
}

class MyRectangle extends MyShape {


private boolean filled;

public MyRectangle() {
super(10, 10, 100, 100, Color.YELLOW);
this.filled = false;
}

public MyRectangle(double x1, double y1, double x2, double y2, Color
color, boolean filled) {
super(x1, y1, x2, y2, color);
this.filled = filled;
}

CS 212: Object Oriented Programming Page 16


public boolean isFilled() {
return filled;
}

public void setFilled(boolean filled) {


this.filled = filled;
}

@Override
public void draw(Graphics g) {
g.setColor(getColor());
if (filled)
g.fillRect((int) Math.min(getX1(), getX2()), (int)
Math.min(getY1(), getY2()),
(int) Math.abs(getX2() - getX1()), (int) Math.abs(getY2()
- getY1()));
else
g.drawRect((int) Math.min(getX1(), getX2()), (int)
Math.min(getY1(), getY2()),
(int) Math.abs(getX2() - getX1()), (int) Math.abs(getY2()
- getY1()));
}
}

public class Main extends JPanel {


private MyShape[] shapes;

public Main(int numShapes) {


shapes = new MyShape[numShapes];
generateShapes();
}

private void generateShapes() {


int numLines = 0, numRectangles = 0, numOvals = 0;
for (int i = 0; i < shapes.length; i++) {
int type = (int) (Math.random() * 3); // 0: Line, 1: Rectangle, 2:
Oval
Color color = new Color((int) (Math.random() * 256), (int)
(Math.random() * 256),
(int) (Math.random() * 256));
double x1 = Math.random() * getWidth();
double y1 = Math.random() * getHeight();
double x2 = Math.random() * getWidth();
double y2 = Math.random() * getHeight();

switch (type) {
case 0:
shapes[i] = new MyLine(x1, y1, x2, y2, color);
numLines++;
break;
case 1:
shapes[i] = new MyRectangle(Math.min(x1, x2), Math.min(y1,
y2), Math.abs(x2 - x1), Math.abs(y2 - y1), color, Math.random() > 0.5);

CS 212: Object Oriented Programming Page 17


numRectangles++;
break;
case 2:
shapes[i] = new MyOval(Math.min(x1, x2), Math.min(y1, y2),
Math.abs(x2 - x1), Math.abs(y2 - y1), color, Math.random() > 0.5);
numOvals++;
break;
}
}
System.out.println("Created " + numLines + " lines, " + numRectangles
+ " rectangles, and " + numOvals + " ovals.");
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (MyShape shape : shapes) {
shape.draw(g);
}
}

public static void main(String[] args) {


int numShapes = Integer.parseInt(JOptionPane.showInputDialog("Enter
the number of shapes to generate:"));
JFrame frame = new JFrame("Shapes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Main(numShapes));
frame.setSize(600, 600);
frame.setVisible(true);
}
}

CS 212: Object Oriented Programming Page 18

You might also like