I have the following abstract Java class:
abstract class AbstractDto {
String id;
public void setId(String id) { this.id = id; }
public String getId() {return id; }
}
I also have class which extends the abstract class:
class SomeDto extends AbstractDto {
@SomeAnnotation
String id;
}
I want to annotate an instance variable derived from an abstract class. I am not sure if this is the way to go as I did it. I know that Java does not provide variable overloading so this is shadowing.
So what happens if I do:
public void go(AbstractDto dto) {
println("dto.id: "+dto.id);
}
AbstractDto dto = new SomeDto();
dto.setId("1234");
go(dto);
Since I do shadowing when I set the id of SomeDto then there is an id
variable inherited from AbstractDto which is still not set.
How can I annotate an instance variable defined in an abstract super class?
Edit: When I do:
SomeDto dto = new SomeDto();
dto.setId("123");
Which id was set the one in AbstractDto or the one in SomeDto? What happens I a method in the Abstract class reads from id which id is then used?
The example you provided is called shadowing , there is no overriding for fields in Java.
More about shadowing could be found in Wikipedia :
In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope.
So, to use your annotation, you can either annotate your id
variable in the abstract class (all inherited classes could use that annotated variable), or just annotate the id
variable of SomeDto
but you have to be aware that it's a new variable (no relation with the id's super class variable)
Regarding your second question:
Which id was set the one in AbstractDto or the one in SomeDto?
The id of SomeDto will be set because the reference variable type of dto
is SomeDto
. To explain more, in the inherited class SomeDto
you defined another id
variable which hides the first one, so each call using a reference to that class or any inherited class of SomeDto
will call the new id
variable defined in the SomeDto
class.
What happens I a method in the Abstract class reads from id which id is then used?
Each call to id
in the abstract class will use the id
in the abstract class, so a method implemented in AbstractDto
and using the variable id
will use the AbstractDto
one.
Annotating instance variables defined in abstract super class:
This is some real life examples where instance variables of abstract classes are annotated:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.