2) Using the concept of abstract class and dynamic method dispatch, write a Java Program that calculates and prints the areas of triangle, square and rectangle.
package Program2;abstract class shapes {
abstract void print();
abstract void calc();
}
class triangle extends shapes {
public int a, b, area;
triangle(int p, int q) {
a = p;
b = q;
}
void calc() {
area = a * b;
}
void print() {
System.out.println("Triangle area" + area);
}
}
class rectangle extends shapes {
public int a, b, area;
rectangle(int p, int q) {
a = p;
b = q;
}
void calc() {
area = a * b;
}
void print() {
System.out.println("Rectangle area" + area);
}
}
class square extends shapes {
public int a, area;
square(int p) {
a = p;
}
void calc() {
area = a * a;
}
void print() {
System.out.println("Square area" + area);
}
}
public class ShapesAbstract {
public static void main(String args[]) {
shapes obj = new triangle(5, 10);
obj.calc();
obj.print();
obj = new rectangle(5, 10);
obj.calc();
obj.print();
obj = new square(5);
obj.calc();
obj.print();
}
}
0 comments:
Post a Comment