Skip to main content

problem with inheritance

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
2 replies [Last post]
mu88
Offline
Joined: 2012-08-30

Good evening,

I have a problem in understanding inheritance between classes and subclasses. This is the current situation:

I've got a class Point with several attributes and methods. The two classes DataPoint and ControlPoint are derived from Point.

There is another class TriangleControl with possesses an object of Point, let's say my_point. This is the constructor:

public TriangleControl (Point cur_point)
{
    my_point = cur_point;
}

In the main function, I do the following:

ControlPoint p1 = new ControlPoint(...);
DataPoint p2 = new DataPoint(...);
TriangleControl tc1 = new TriangleControl(..., p1);
TriangleControl tc2 = new TriangleControl(..., p2);

This works fine!

But if I do the following, it crashes:

ControlPoint p1 = new ControlPoint(...);
DataPoint p2 = new DataPoint(...);
Point p3 = p1; or Point p3 = p2;

The Eclipse-Error-Message is "type mismatch: cannot convert from ControlPoint/DataPoint to Point"

Can anyone explain me, why the assignment in the constructor works, but not the direct assignment? Or am I doing something wrong?

Kind regards and thanks in advance!

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
shingnpr
Offline
Joined: 2012-09-21

It works properly.
Please see the code 4 ur reference.

public class Point {

public void display() {
System.out.println("Point Display Method");
}
}

public class ControlPoint extends Point {
@Override
public void display() {
System.out.println("ControlPoint Display Method");
}
}

public class DataPoint extends Point {
@Override
public void display() {
System.out.println("DataPoint Display Method");
}
}
public class TriangleControl {
private final Point my_point;

public TriangleControl(Point cur_point) {
my_point = cur_point;
}

public void display() {
my_point.display();
}
}
public class TestInheritance {

/**
* @param args
*/
public static void main(String[] args) {
ControlPoint p1 = new ControlPoint();
DataPoint p2 = new DataPoint();
TriangleControl tc1 = new TriangleControl(p1);
tc1.display();
TriangleControl tc2 = new TriangleControl(p2);
tc2.display();
Point p3 = p1;
p3.display();

}
}
****************OUTPUT***************
ControlPoint Display Method
DataPoint Display Method
ControlPoint Display Method

Please refer this code and see if u have done something wrong.

mu88
Offline
Joined: 2012-08-30

Hi,

thank you for your response! You are absolutely right, the code works.

My problem was - and I really feel ashamed - that I've imported the class java.awt.Point simultaneously, but I didn't notice and Eclipse didn't warn me.
So I tried to create a class that already existed, which of course can not work.

Problem is solved ;)

Kind regards!