Sign in to follow this  
Cuajin

[Java] Abstract class problem

Recommended Posts

Cuajin    155
Hi.

I have a Point3D class, Shapes abstract class, and a Sphere that extends Shapes.

I want Shapes to have a member object from Point3D.

[CODE]
public class Point3D
{
private float x, y, z;
public Point3D(float x, float y, float z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
[/CODE]

[CODE]
public abstract class Shape
{
private Point3D point;

public Shape()
{
point = new Point3D() ;
}
}
[/CODE]

[CODE]
public class Sphere extends Shape
{
private double radius;
public Sphere(float x, float y, float z, float radius)
{
// How do I pass the x, y ,z values to point3D?
}
}
[/CODE]

I want to create the sphere but by making sure that I pass values to the point3D, how do I do it?

Also I have a feeling that putting a constructor on an abstract class is wrong.

Please help.

Share this post


Link to post
Share on other sites
dmatter    4821
[quote name='Cuajin' timestamp='1332875672' post='4925780']
I want to create the sphere but by making sure that I pass values to the point3D, how do I do it?

Also I have a feeling that putting a constructor on an abstract class is wrong.
[/quote]

Constructors on abstract classes are quite common and is not inherently wrong in any way.
The solution therefore is to add a constructor to Shape that takes the x, y, z components and initialises the Point3D member. You can call the constructor from Sphere using the super keyword: super(x, y, z);

As an aside, the code you posted shows you attempting to use a default constructor on the Point3D class but no such constructor is defined; you would need to explicitly add a default constructor for that code to compile.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this