简体   繁体   中英

Dynamic class reference variable JAVA?

I am new to java and still got a lot to learn. I have embedded C programming experience but totally new to object oriented programming.

I got the following that i need to understand. When you create a class in Java it is the blueprint of an object you are going to create. And say i have a GUI with a button that creates a new bicycle after i have clicked the create new bicycle button you enter all the instance variables that it asks for in your GUI etc.

Then when you finish with say clicking on a complete button a object is created. With all the data you supplied in your GUI to fit the blueprint.

So in your actionlistener when the complete button is pressed a piece of code like Bicycle bike = new Bicycle(); should run. But bike is static and you never know how many entries of bicycle's there is going to be. So how can the reference variable be made dynamic or act like its dynamic?

Sorry let me try and clear it up with the following.

public void actionPerformed(ActionEvent e) {
            Bicycle bike = new Bicycle();
    }

this is a action which is performed when Jbutton is pressed. This will create an object named "bike". But what happens when button is pressed again?Will it just override the previous object named bike?

And you dont know how many objects of bicycle type the user will create by pressing the button. So i was wondering if something like a array can be used in the following way

String bike[] = {"bike1","bike2,"bike3"};
for(int i=0;i<3;i++){
    Bicycle bike[i] = new Bicycle();
}

or use a 'array list' because ultimately you wont know how many object will be created?

So how can the reference variable be made dynamic or act like its dynamic?

This is how reference behave by default. There is nothing static about them. Even if you use a static field it is not static in the sense C would understand it. It doesn't exist until the class is loaded and it can exist multiple times if the class is loaded in different class loaders. It can even go away if the class loader is unloaded.

If your field is not static it is even more dynamic esp if it is a local variable.

If you want a variable that can hold references to multiple Bicycle instances, you can use a Collection such as List :

List<Bicycle> bikes = new ArrayList<Bicycle>();

Then, each time a new Bike instance is created, you add it to the List :

Bicycle bike = new Bicycle(); 
bikes.add (bike);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM