PDA

View Full Version : Java Inheritance question


Cat22
08-10-2006, 05:47 PM
Hi, i have following code that works OK:

public class Building {

protected String name;

A(String name){
this.name = name;
}
public void printSpecs() {}
}

and two inherited classes :


public class House extends Building {
protected double maxDimension;
House (String name, double maxDimension) {
super(name);
this.maxDimension= maxDimension;
}

public void printSpecs()
{
System.out.println(maxDimension);
}
}

public class Castle extends Building {

protected double maxWeight;

Castle (String name, double maxWeight) {
super(name);
this.maxDimension= maxWeight;
}

public void printSpecs()
{
System.out.println(maxWeight);
}
}

i have array of objects
HashMap <int, Building > builds = new HashMap<int, Building >();
and some of them are of type "House" and some "Castle"

when i do following:
Building myBuild = builds .get(x);
myBuild.printSpecs();

everything works: specs are printed according to class type.

Now, the question: I want to add function

int GetSpecs() {}
to "father" class "Building" so that result will be returned by inherited class (similar to function printSpecs)
BUT, when i add such empty function i get error "function GetSpecs must return results".
So, what's the right syntax/way to do it ?
Thanks

Aradon
08-10-2006, 06:01 PM
The reason it asks for a return type is because you can't have an empty method with a return type of int.

int GetSpecs() {}

You could only do this if the class was abstract (if I remember right). but if it was abstract then you would want to impliment it in the child classes.

Cat22
08-10-2006, 06:08 PM
I will definitely implement getSpecs() {} in child classes, but what should i write in the main class?

Jarl
08-15-2006, 03:02 PM
My Java is a little rusty but as the previous poster mentioned you should just be able to define the superclass abstract:

public abstract class Building {
protected String name;

Building(String name) {
this.name = name;
}

And include your abstract method like so:

public abstract int getSpecs();

You will need to provide the implementation for this method in each subclass (or else also define the subclass as abstract) that inherits from Building though. Also you won’t be able to instantiate a Building object itself—which would stand to reason.

Hope that helps.