C# Lab Exercise

advertisement
Computer Programming-2 (CS2300)
Java Lab Exercise #09
Abstract Class & Polymorphism
Abstract Class &
Polymorphism
Student Name & Number
Instructor:
Lab Session-#09
Evaluation:
Date:
Q1. Predict the output of the following program:
Program
Output
class Fruit {
public void show() {
System.out.println("Fruit");
}
}
class Banana extends Fruit {
@Override
public void show() {
System.out.println("Banana");
}
public void makeBananaTree() {
System.out.println("Making a tree");
}
}
public class Application {
public static void main(String[] args) {
Fruit banana = new Banana();
banana.show();
// The following WILL NOT work;
// Variables of type Fruit know only
// about Fruit methods.
// banana.makeBananaTree();
}
}
1
Computer Programming-2 (CS2300)
Abstract Class & Polymorphism
Lab Session-#09
Q2. Write a program (Abstract)
Define an abstract class named Shape containing:
- An instance variable named color of type string.
- A method named setColor that takes one parameter of type string which initializes the
instance variale color.
- A method named getColor that returns the value of instance variable color.
- An abstract method named Area that has a return type double.
Define another class named Rectangle which is extended from class Shape containing:
- Two instance variables named Length, Width of type int.
- A full parameterized constructor which initializes all the instance variables of both the classes
(by calling setColor method).
- An overridden method named Area which returns the calculated area of the rectangle.
- A method named displayArea which displays the area of rectangle.
Define a third class named TestDemo contains a main method that test the functionality of the
above classes.
2
Computer Programming-2 (CS2300)
Abstract Class & Polymorphism
Lab Session-#09
Q3. Write a program (Interface & Polymorphism)
Define an interface named Shape containing:
- Declare a method named area which has a return type double.
- Declare a method named volume which has a return type double.
Define another class named Cube which implements Shape containing:
- An instance variable named x of type int (with value = 10).
- Implement the method named area which returns the calculated area of the cube (i.e, 6*x*x).
- Implement the method named volume which returns the calculated volume of the cube (i.e,
x*x*x).
Define another class named Circle which implements Shape containing:
- An instance variable named radius of type int (with value = 10)..
- Implement the method named area which returns the calculated area of the circle (i.e, 𝐴 =
𝜋𝑟 2 ).
- Implement the method named volume which returns the value 0.
Define a third class named PolymorphismTest which contains a main method that test the
functionality of the above classes.
(Hint: Use 1-D array of type Shape and create the objects of both the classes as the array
initializers.)
3
Download