Java – extends objects and inherits all variables
Suppose I have a car like object with 30 variables, from maximum speed to color I want to create a mycar object (class mycar extension car), which is basically the same thing, except that it stores more information
I can't create mycar objects immediately (because only a few of the thousands of car objects will become mycar objects), unless I leave other fields blank, but it doesn't seem professional And neither create a constructor with 30 parameters nor set 30 parameters through method calls
So, is there any way to easily inherit all variables from superclass objects?
PS: my plan is not about cars, but I think it will be a simpler example
edit
Thank you for your reply. They are helpful to my program, but they are not applicable to this special problem The builder seems to have no benefit because my cars have no default values for variables Every time a car is built, all variables are filled in (this is required to build a "fact table")
The envelope is an interesting design, but I still need to copy all the variables in the subclass constructor I hope there is a way around this The template also requires me to copy all variables one by one
In my program, subclasses act as "wrapper classes" in search engines The subcategories are the same as ordinary cars, but they have "ranking scores" My program is designed to display regular cars. By extending them, I can easily display subclasses and sort by scores at the same time
I want to create a new object anyway, because I can perform multiple searches on the same car list Therefore, editing variables in the original vehicle is not an option
Maybe there is a better solution to this problem, but now I think I have to pass the superclass object to the constructor and copy all the variables there
Thank you for your help!
PS: I just thought, maybe I can throw all variables into HashMap So I can use it Get (Varname) to access them, I just need to pass a HashMap variable to the subclass I have to invest a lot in the downlink, because the variables are a mixture of strings, integers, doubles, etc What do you think, can it accept the coding style?
Solution
Effective java version 2, item 2: consider the builder when facing many constructor parameters
If you are facing a constructor with too many parameters, you may need to look at: builder pattern Our idea is to set only the fields you want / know to the builder without having to consider the optional fields, or the fields you want to use the default values, and then call build () to construct the actual objects. See the java example in this article
Once you set this mode, you can build cars in this way (pay attention to the clean structure):
Car car = new Car.Builder(required_param1,required_param2) .color(RED) // optional params .topSpeed(300) .zeroToHundred(2) .build();