Simran Vishisht Java Assignment 2
Simran Vishisht Java Assignment 2
ASSIGNMENT: 2
else
return stck[tos--];
}
}
OUTPUT:
3. Create a class TwoDim which contains private members as x and y coordinates in package P1. Define
the default constructor, a parameterized constructor and override toString() method to display the co-
ordinates. Now reuse this class and in package P2 create another class ThreeDim, adding a new
dimension as z as its private member. Define the constructors for the subclass and override toString()
method in the subclass also. Write appropriate methods to show dynamic method dispatch. The main()
function should be in a package P.
Answer:
TwoDim.java :
package P1;
public class TwoDim {
private int x,y;
public TwoDim()
{
x=0;
y=0;
}
public TwoDim(int a,int b)
{
x=a;
y=b;
}
public String toString()
{
return "Coordinates of x and y are "+x+ " and "+y+"\n";
}
}
TwoDim.java :
package P1;
public class TwoDim {
private int x,y;
public TwoDim()
{
x=0;
y=0;
}
public TwoDim(int a,int b)
{
x=a;
y=b;
}
public String toString()
{
return "Coordinates of x and y are "+x+ " and "+y+"\n";
}
}
Demo.java:
package P;
import P1.*;
import P2.*;
public class DEmo
{
public static void main(String args[]){
TwoDim obj;
obj=new TwoDim(9,4);
System.out.println(obj.toString());
obj=new ThreeDim(6);
System.out.println(obj.toString());
}
}
4. Define an abstract class Shape in package P1. Inherit two more classes: Rectangle in package P2 and
Circle in package P3. Write a program to ask the user for the type of shape and then using the concept
of dynamic method dispatch, display the area of the appropriate subclass. Also write appropriate
methods to read the data. The main() function should not be in any package.
Answer:
Shape.java:
package P1;
abstract public class Shape
{
abstract public void area();
}
Rectangle.java:
package P2;
public class Rectangle extends P1.Shape
{
double length,breadth;
public Rectangle(double a,double b)
{
length=a;
breadth=b;
}
public void area()
{
System.out.print("Area of Rectangle is "+length*breadth+"\n");
}
}
Circle.java:
package P3;
public class Circle extends P1.Shape
{
double radius;
public Circle(double a)
{
radius=a;
}
public void area()
{
System.out.print("Area of circle is "+(3.14*radius*radius));
}
}
DemoShape:
import P1.Shape;
import P2.Rectangle;
import P3.Circle;
public class DemoShape
{
public static void main(String args[])
{
Shape obj;
obj = new Rectangle(5, 7.4);
obj.area();
obj = new Circle(8);
obj.area();
}
}