Java Questions

JC0133

Senior member
Nov 2, 2010
201
1
76
I have a couple of quick questions.

Using inheritance how can you call the toString method from the parent class in the child class?

How does the getClass() function work? Like I have seen a return statement in a toString method say

return getClass() + "Weight = " + weight;
 

beginner99

Diamond Member
Jun 2, 2009
5,315
1,760
136
I have a couple of quick questions.

Using inheritance how can you call the toString method from the parent class in the child class?

How does the getClass() function work? Like I have seen a return statement in a toString method say

return getClass() + "Weight = " + weight;

If you override toString() in the child class you can't (and if you have to do this your design is flawed), if you don't it will automatically take that of the parent class. Note that all Java objects have a parent class: class Object. So if you don't override toString() it will always take the one from class Object.
This is also why all your objects have the getClass method. It is inherited from Object.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
You can call a parent's method from within the class, but you can't do it from outside the class.

Code:
public class test {
	
	public static void main(String[] args) {
		
		B b = new B();		
		
		//prints "B"
		System.out.println(b.toString());
		
		//prints "A"
		System.out.println(b.callParentToString());
		
		C c = new C();
		
		//prints "C"
		System.out.println(c.toString());
		
		//there is no way to make the 'c' object output "A"
	}
	
	public static class A {
		@Override
		public String toString() {
			return "A";
		}
	}
	
	public static class B extends A {
		@Override
		public String toString() {
			return "B";
		}
		
		public String callParentToString() {
			return super.toString();
		}
	}
	
	public static class C extends A {
		@Override
		public String toString() {
			return "C";
		}
	}

}
 

Ancalagon44

Diamond Member
Feb 17, 2010
3,274
202
106
Yeah I was going to say, you would need to use the super keyword, but that can only be done from within the class itself.
 

Borealis7

Platinum Member
Oct 19, 2006
2,901
205
106
If you override toString() in the child class you can't (and if you have to do this your design is flawed)
what?? i think i dont understand you...lets say i have a Car object, and Red Car, Blue Car extending it. Car has a toString() that says "i'm a car" and i want the Red and Blue cars to say "i'm a car, and my color is (red/blue)".

the way to implement it would be to override toString with a call to super.toString() and concatenating the rest to it. why is that flawed? thats the whole point of inheritance:
perform your super's code, and extend it with your additions to minimize code duplication.

also to add to Leros's code, a common mistake with polymorphism is if you write something like:

A c = new C();
println(c.toString());

it will output "C". its always the right side that counts.
 
Last edited:

Ancalagon44

Diamond Member
Feb 17, 2010
3,274
202
106
With inheritance, you dont often "extend" inherited code so much as completely overwrite it. Basically, I dont often see the super keyword being used. The most common use for the super keyword, or the equivalent in C#, is to call a constructor in the parent class. Not commonly done in actual methods, overwritten or not.

In any case, I would think a better solution would be to have a car class that has certain properties, such as make, model, year, colour and engine.

Then, car.toString() will print out a message saying I am a Make Model manufactured in Year. My colour is Colour and my engine is Engine.

Replace the words with first letter caps with actual get() calls, or uses of the private variables if you prefer.

That way, you can use the Car class to do exactly what you want without inheritance (in fact I dont think your example is a good use of inheritance at all). You could also create a Vehicle class for Car to inherit from. An appropriate subclass for Car could be SUV, for instance.
 

Borealis7

Platinum Member
Oct 19, 2006
2,901
205
106
i agree its not a great example, but the point that i was making is that extending actually does the opposite of its name, its making the class more specific. the more you extend, the more "properties" you "bolt down". the higher you go up the inheritance chain, the more abstract the object gets. that's what i believe is the point of inheritance.

regarding your suggestion for the Car object with the private members, the way you do it you basically "force" everyone who extends your car to carry around those extra members even if they don't need them (for instance i just wanted a color, not an engine etc') so i think this implementation is more memory wasteful (for far more complex objects obviously...), but that's just my opinion.
 
Last edited:

trexpesto

Golden Member
Jun 3, 2004
1,237
0
0
No reason to extend if all you are doing is setting properties that the parent already has.
What you are extending (aka overriding) is the parent's implemented functionality.

An example parallel to the OP's toString() example is paintComponent().
Often you will want your custom component to paint the background, border, and the contained components, and THEN do some custom painting.
Say drawing a line to the location of the mouse cursor:

Code:
protected void paintComponent(Graphics g){
     super.paintComponent(g); // draws bg, and calls paintBorder() and paintChildren()
     g.drawLine(startPoint, mouseLoc);
}


In java, using the super keyword is not always necessary, as it is automatically assumed if the child class does not have the method. So it is often there, implied, similar to 'this'.

It may be better, depending on the application, to make Car class extend AbstractVehicle which in turn implements some interfaces like ColorChangeable.
It can create a single point of maintenance so that you don't have to implement changeColor() in each vehicle, then forget to do it somewhere and create more headaches.
Sometimes there will even be classes that implement methods from a superclass with a no-op only because they have to in order to take advantage of the super's other qualities:
Code:
public class MouseMotionPanel extends JPanel implements MouseMotionListener{

    public MouseMotionPanel(){
        this.addMouseMotionListener(this);
    }

    public void mouseDragged(MouseEvent me) {
        Point pt = me.getPoint();
        System.out.println("Point is "+ pt.x + "," + pt.y);
    }

    // No-op, but required to implement MouseMotionListener
    public void mouseMoved(MouseEvent me) {
    }
}
 
Last edited:

beginner99

Diamond Member
Jun 2, 2009
5,315
1,760
136
what?? i think i dont understand you...lets say i have a Car object, and Red Car, Blue Car extending it. Car has a toString() that says "i'm a car" and i want the Red and Blue cars to say "i'm a car, and my color is (red/blue)".

the way to implement it would be to override toString with a call to super.toString() and concatenating the rest to it. why is that flawed? thats the whole point of inheritance:
perform your super's code, and extend it with your additions to minimize code duplication.

also to add to Leros's code, a common mistake with polymorphism is if you write something like:

A c = new C();
println(c.toString());

it will output "C". its always the right side that counts.

Well I understood the question differently. of course with your interpretation my comment seems silly. I thought from outside the class in a scenario were you don't really now the specific implementation of car.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
Well I understood the question differently. of course with your interpretation my comment seems silly. I thought from outside the class in a scenario were you don't really now the specific implementation of car.

Knowing that an object is of type Car tells you that is has a certain set of methods and properties you can use (the ones defined in the Car class and its parent class).

You don't know if those methods/properties that you will actually end up using come from the Car class, a parent of the Car class, or a child of the Car class. It doesn't matter.
 

Ancalagon44

Diamond Member
Feb 17, 2010
3,274
202
106
i agree its not a great example, but the point that i was making is that extending actually does the opposite of its name, its making the class more specific. the more you extend, the more "properties" you "bolt down". the higher you go up the inheritance chain, the more abstract the object gets. that's what i believe is the point of inheritance.

regarding your suggestion for the Car object with the private members, the way you do it you basically "force" everyone who extends your car to carry around those extra members even if they don't need them (for instance i just wanted a color, not an engine etc') so i think this implementation is more memory wasteful (for far more complex objects obviously...), but that's just my opinion.

Yes but why would you need to inherit from it at all? These bolt down properties, lets face, belong to all cars. Name me a car that does not have a colour or an engine - is it still a car?

Now if there was a property that not all cars have, for instance a motor home might have a fitted kitchen, then you would inherit from it, as that is a more specific class of Car (if you want to call it a car).

Creating a RedCar and BlueCar class just to change one property - colour - which both subclasses have anyway is a complete waste of time.
 

Borealis7

Platinum Member
Oct 19, 2006
2,901
205
106
we're both saying the same thing, the Car example is not nearly complex enough to justify the inheritance.

lets say you have 2 objects that extend Thread: a SocketListenerThread and DBTablePollingThread (i just made those up, no relation to any existing objects). these 2 don't have much in common and use different resources.
the DBTablePollingThread doesnt need a Socket member and the SocketListenerThread doesnt need a JDBC Connection member. all they have in common is that they override/implement Thread/Runnable Run() function.
 

Ancalagon44

Diamond Member
Feb 17, 2010
3,274
202
106
Yes then obviously you wouldnt have that member as part of the class they inherit from.

But in the car case, inheritance does not make sense.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
Factoring the characteristics of classes in an inheritance hierarchy is a subjective process. It's more art than science. But there are some pretty clear guidelines. If you find yourself with a subclass that differs from its parent class only by constraining the value of an inherited property (i.e. Color = Blue) that ought to set off alarms. If you need to constrain a property value for a set of objects then you do that with something like a factory pattern. On the other hand, a subclass of Car called PatrolCar that adds Lights, Siren, and Shotgun properties makes perfect sense.