This has bothered me for a long time, so I thought I’d go ahead and ask.
If I write
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
new Shape();
new Triangle();
}
public static class Shape
{
static String name = "shape";
Shape()
{
printName();
}
public void printName()
{
System.out.println( name() );
}
public String name()
{
return name;
}
}
public static class Triangle extends Shape
{
static String name = "triangle";
public String name()
{
return name;
}
}
}
then the output is
shape
triangle
But if I write
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
new Shape();
new Triangle();
}
public static class Shape
{
static String name = "shape";
Shape()
{
printName();
}
public void printName()
{
System.out.println( name );
}
}
public static class Triangle extends Shape
{
static String name = "triangle";
}
}
then the output is
shape
shape
In the first version, I have to copy/paste the same function getName() over and over into every subclass. There’s has to be a better way. What do I need to change in the second example?
static fields aren’t accessible from parent classes. The class
Shapedoesn’t “see” the static fieldnameof the classTriangleand uses his own static fieldname.UPD: You ask: what do you need to change in the second example? More specifically, your first example is a correct “fixing” of your second example. The only correct way is using some getter method like your
name()method.UPD2: (from my commentary): Well, another way: forgive about any kind of field
name. Use instead a method calledname()(not static!) which will return in each class the needed name. Justreturn "shape";orreturn "triangle"in them;