Java Newbie qustion

Status
Not open for further replies.

simmadown

Seniorius Lurkius
34
I am trying to do a simple exercise, of creating a derived class from a base class, but when I try to compile the derived class, I get this error:
cannot resolve symbol
symbol : constructor Animal ()
location: class Animal
public class Dog extends Animal

There is a carrot below "class" in the last statement depicting the error. Anyone know why this is? I copied the code directly from my textbook.
 

simmadown

Seniorius Lurkius
34
This is the base class code:

public class Animal
{
public Animal(String aType)
{
type = new String(aType);
}


public String toString()
{
return "This is a " + type;
}

private String type;
}

This is the derived class code:

public class Dog extends Animal
{
private String name;
private String breed;
}

They are both in the same folder. I can compile Animal.java, but not Dog.java. I am building a more complex program, that has to use polymorphic methods, and when I tried creating the derived classes, I got a similar error. So I tried to just code the example to see if that would work, and I got the same error.
 

gumbo

Ars Tribunus Angusticlavius
6,107
Try creating a constructor that accepts a String argument.

I haven't messed around with this type of extension lately, I'll mess around with it tonight.

Edit: Like newton_meter said, itm compiles fine with a no-arg constructor in Animal. You can also add the constructor

Code:
public Dog (String a) {
    name = a;
}

into Dog.java, and it will work. Also, you do not have to do
Code:
type = new String(aType);
you can do
Code:
type = aType;

This is because to pass in the String to Animal's constructor, you must have created, avoiding the null pointer.

gubmo

[This message was edited by gubmo on March 26, 2002 at 21:44.]
 

skriefal

Ars Scholae Palatinae
1,056
This is because to pass in the String to Animal's constructor, you must have created, avoiding the null pointer.

Not only that, but it's also unnecessary because Strings are immutable.

The usual reason for copying data passed into a constructor is so that if you change the object's internal state at some later point, you don't adversely affect code elsewhere that may also hold a reference to the same object. But Strings are immutable, so you cannot change them. Thus, copying them is a waste of time and memory.
 
Status
Not open for further replies.