• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Accessing object content from another class

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Q1) Why can't I access the car1 object contents? See commented code below?




Q2) If I have 3 Classes... ClassA, ClassB, & ClassC.
In ClassA if I create an object of ClassB, can I access the ClassB object from ClassC? I've been trying to do this but no luck. If it is possible to do so how do I need to do it?

Thanks.
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator




Graham Sills wrote:Q1) Why can't I access the car1 object contents? See commented code below?





 Because getCarMake is a method. You are suppose to use getCarMake() Not just getCarMake in line 22 of your code.

 Check your code again. Check what your getCarMake method is even returning.

 More so, within your  Reservation class you will not be able to access your Car instance variable like you are using it.

I am assuming you know that you can only use one public class in a file, if all your class are in a single file.
Am also assuming that your "Main" class with main method is in a different file.



Q2) If I have 3 Classes... ClassA, ClassB, & ClassC.
In ClassA if I create an object of ClassB, can I access the ClassB object from ClassC? I've been trying to do this but no luck. If it is possible to do so how do I need to do it?

Thanks.


How are you trying to achieve that? Is the question.
 
Graham Sills
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes the is correct in my main program. I just edited it for this post.

The two classes are in difference files. And I have the main method in another class which calls the Reservation class.

You say "within your  Reservation class you will not be able to access your Car instance variable like you are using it. "
1) Why?
2) What will I need to do so I can access the car instance variable?
 
timothy adigun
Greenhorn
Posts: 19
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:Yes the is correct in my main program. I just edited it for this post.

The two classes are in difference files. And I have the main method in another class which calls the Reservation class.

You say "within your  Reservation class you will not be able to access your Car instance variable like you are using it. "
1) Why?


Because the Car instance variable car1 is local to the  Reservation class constructor. Did you see that?
And so you can't access it outside the class constructor.


2) What will I need to do so I can access the car instance variable?



Change what your Car class method getCarMake to return correct class variable. There is nothing like carID, in the class you posted here.

Hope that helps.
 
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:Q2) If I have 3 Classes... ClassA, ClassB, & ClassC.
In ClassA if I create an object of ClassB, can I access the ClassB object from ClassC? I've been trying to do this but no luck. If it is possible to do so how do I need to do it?

this is quite not clear.can you please show us your code so that we will know what actually you have done.

Kind regards,
Praveen.
 
praveen kumaar
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Though i would recommend you to do some changes-
-->why are you using a name carMake for the variable you can use some intentional name like carName which let others know that it represent name of car.
-->method carMake can also be well named like for ex--buildCar(),designCar(),makeCar()...as you like.
-->declare a variable named carID.
-->you are not initializing the variables in your constructor rather you have a setter to do it,it is a very bad practice suppose the user accidentally calls the getter on the instance without calling a setter method,what will happen,he would get a NullPointerException.
-->Think about immutability of your class.why do you thing it should have a setter.practically when a car is designed it was given a name and that name remains the same,though in future release its new model may come but in that case the all new object is used.coding is not something different from it indeed it was invented to solve the practical problems.so you should well interpret it with the steps that exists in our practical world.
-->i am assuming your Reservation class is related with reservation of Car.now think when you go for the reservation what are the necessary things,concisely it is-the car you want to reserve and a ID(their may be other things too,that is up to your policy for reservation).so why don't you declare a Car reference below the ReservationID,declare it.and set them in a Reservation constructor.it will solve your problem.


Kind Regards,
Praveen.
 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have you created the object as a local variable in a method? In that case it has no existence outside the method. What you probably really need is a 3rd class, which has a method which starts your app off and creates objects in a method. Rather like creating the Kettle objects here. Add another class to that app, and create (maybe) Water instances in that method. Forget the bit about annotations. You can find a similar app which goes wrong here (Corrections later in the same discussion). There are better examples which I have written about kettles, but I can't seem to find them now. You might find them by searching my posts for KettleDemo.
 
Graham Sills
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The program is a car rental system. There are some errors because I've extracted the code and modified things a little so I can post something concise and easier to understand here. The mistakes called out here are not in my actual files, I just didn't edit my original post correctly.

 

---------------------------------------------------------

OK someone mentioned I cannot access the car1 object because I have created it in the Constructor. OK then, however if I create it outside of the Constructor I still cannot access the object contents. Why? The error I get is when I enter the dot (car1.). I can't access anything in the car1 object.

 

I have an AutoRental class which has the main method. It's a console application where I use a swtch statement to control the program flow.  


So I plan on having some way to record data in a textfile, using object serialization. I have no idea about right now that so for the time being I will just create an object when the application starts temporarily so I can actually test my program as I make it. I'm learning as I go along so I'm doing it bit by bit. Right now I'm just stuck on understanding how and where I can create/access objects.  I just want to understand but I just don't get it.
Thanks
 
timothy adigun
Greenhorn
Posts: 19
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:The program is a car rental system. There are some errors because I've extracted the code and modified things a little so I can post something concise and easier to understand here. The mistakes called out here are not in my actual files, I just didn't edit my original post correctly.

 



Be that as it may. In the light of my previous assumption and your assertion.

In the Reservation class, you could just do so:

 


OK someone mentioned I cannot access the car1 object because I have created it in the Constructor. OK then, however if I create it outside of the Constructor I still cannot access the object contents. Why? The error I get is when I enter the dot (car1.). I can't access anything in the car1 object.

 





You can't just pulled that up in a class. Just unclad without no method or a block.

And I thought, someone also mentioned it that you should initialize your class variables in your constructor. Which is a good practice.

Try the option I gave you and see what you have then let us talk about other part of your code.


 
praveen kumaar
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you have done:

Do some chages:


Kind Regards,
Praveen.
 
timothy adigun
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

praveen kumaar wrote:you have done:




His Reservation class doesn't have such Constructor, he may find it difficult using that.

In as much as I view this constructor as a good one, without showing him how to use it, he might confuse the OP more.

Just saying though.
 
praveen kumaar
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

His Reservation class doesn't have such Constructor, he may find it difficult using that.
In as much as I view this constructor as a good one, without showing him how to use it, he might confuse the OP more.
Just saying though.


In that case your suggestion will be a good alternative.

Kind regards,
Praveen.
 
praveen kumaar
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@timothy,apologies for not mentioning your name in quotes.
 
timothy adigun
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

praveen kumaar wrote:@timothy,apologies for not mentioning your name in quotes.



Please, you don't have to. All am here for is to help. How that is done and achieved is secondary.
I appreciate the help you are giving here.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:. . .  . . .

Please only post the exact code you are using in the code tags. The comment makes the line too long and the whole discussion becomes illegible to anybody with a small screen, e.g. the mobile view. Please put that sort of thing in the text: “There is an error in line 22 ...” You shlou‍ld also post the exact error message. We ahve seen those messages before and we know what they mean; the more details you give us, the faster we can help.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

praveen kumaar wrote:you have done:
--->here you may have got error identifier expected.it means your code needs some kind of indentifier
so that during runtime jvm can identify your code.identifier can be-static initializer,methods,
constructor,instance initializer...

I am finding that difficult to understand. Does it mean that you think there is a statement outside a method, etc. I have moved the code tags because the comment shouldn't be inside the tags.

Do some chages: ...


Kind Regards,
Praveen.

Why are you setting the make of a Car object inside the Reservation constructor? The Car object ought to have a make already, and setting make is a matter for the Car class, not any other classes.
 
praveen kumaar
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell wrote:I am finding that difficult to understand. Does it mean that you think there is a statement outside a method, etc. I have moved the code tags because the comment shouldn't be inside the tags.


yes,please have a look here,this is what OP does in his previous post:

so i just let OP know that he is not using any identifier for....

Campbell wrote:Why are you setting the make of a Car object inside the Reservation constructor? The Car object ought to have a make already, and setting make is a matter for the Car class, not any other classes.

i just have think about it and found it worth doing such changes.

Kind Regards,
Praveen.
 
Graham Sills
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK thanks for replies.

Timothy posted this:



It works but why does it work?  The only difference between that and my original is that the object reference variable was declared the constructor. OK but I don't understand why it needs to be like that? I guess I need to understand why my original code did not work and how this option works?
The error I was getting was "Cannot resolve symbol 'car1'".
Praveen you mention it's because I'm not using an identifier.... what do you mean by that?

Campbell wrote:
Why are you setting the make of a Car object inside the Reservation constructor? The Car object ought to have a make already, and setting make is a matter for the Car class, not any other classes.


Fair question. Yes it should be created beforehand and I plan to (later on when my basic program works). I plan to use object serialization but I need to do it piecemeal because I am just learning Java and I'm creating the objects when the program begins initially... to get me going and make my basic project work. (I need to have some cars available to be able to test my program as I build it). Why do I have that code in the Reservation class... good question. The answer is because I don't know where else to put it.

Here is a link to my class diagram: https://i.imgsafe.org/d8befede19.png
Maybe I am missing something or maybe I am doing it wrong.

In relation to creating cars to "reserve/book", my plan is to:
1) Doing why I'm doing now... creating them one by one by creating a new object for each car. And yes, I don't know where (what class I should be doing this in). Maybe I am missing a class where I should be doing this.
2) Once this works ok, I'll create an ArrayList and have multiple car objects in here. And incorporate this into my project.
3) Once that works I'll research and try to get object serialization incorporated so I can just read in a text file with the car details and this can be used to create the car objects and automatically put them in the ArrayList.

Whatever I do I just want to make sure I understand it, it's the only way I'll learn.
I appreciate the help given by everyone so far.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The difference between your version and the one you were shown that works is scope and visibility. In your version, you declared the Car inside your constructor. That means the scope/visibility of, and therefore access to, that variable is limited to code that's inside the constructor. Outside the constructor, that Car reference does not exist and cannot be used. Therefore, you can't access that Car reference from the other method because to that other method, that reference does not even exist.

In the version that works, the Car reference variable is declared at the class level. Therefore it is visible to all the methods of that class. In the constructor, a new Car object is assigned to that reference variable. Any method of the class can then use that reference variable to get to that new Car object created in the constructor.

Think of the braces that mark the start and end of each part of your program (class, method, if, loop, etc) as "walls" that keep things declared inside them accessible only to other things inside them. For methods, loops, if statements, and other flow control statements, those walls make any variable declared inside them local and therefore private to that method or statement. So, when you declare the Car inside your constructor, only code that comes after that declaration inside your constructor can see it. Code inside the constructor or method that comes before the variable is declared cannot even see it--how can it, the variable does not exist yet--because code can only see what already happened, not what's still about to happen. Any code outside the braces that wall in the constructor's code will not be able to see that Car reference. It's just like how you can't see things inside the walls of your neighbor's house, or even things in his backyard if he has an eight-foot wall around it.

For classes, there's a little more freedom. The same kind of restrictions exist for things declared within the {...} walls of your class (which are like the hypothetical fences around your neighbor's house) except you can choose to allow access to some things by declaring them public, protected, or package private (the default when you don't specify a visibility/access modifier). This is like your neighbor telling you that you can reach over the fence and pet his dog but only because you're a trusted neighbor (like package private access). Or if your neighbor only lets his kids and grandkids swim in his pool (protected access). Or if your neighbor lets anyone and everyone at all come and play basketball with the hoop that's in his driveway (public access). Anything at the class level that's declared as private will be accessible only to things within that class.

Does that make sense?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:
It works but why does it work?  The only difference between that and my original is that the object reference variable was declared the constructor. OK but I don't understand why it needs to be like that? I guess I need to understand why my original code did not work and how this option works?
The error I was getting was "Cannot resolve symbol 'car1'".



As a few ranchers already mentioned; In the original case, you declared a local variable. In the latest case, you declared an instance variable. Do you know the difference between the two variable types?

In the case of a local variable, the scope of the variable is only for the block that it is declared. And since, you declared it in the constructor, it can only be used in the constructor.

Henry
 
Greenhorn
Posts: 7
Android PHP AngularJS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Right now I can not test your code but want to ask where is your Main class? Primarily, it seems there are so many changes.
 
Graham Sills
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok I am semi there. I now understand the main problem I had which was declaring the object reference variable in one method and trying to access it in another, so I needed an instance variable instead of a local variable. Thanks for explaining.

praveen kumaar said:
why do you think it should have a setter.practically when a car is designed it was given a name and that name remains the same,though in future release its new model may come but in that case the all new object is used.


The application is for a front desk auto rental system, for example at an airport. So at some point I want to write code to allow the admin user to add new cars to their inventory.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1) I still do not understand why the following code does not work. The car1 object is created as an instance variable. So why can't I set the contents in the line below it?

Timothy wrote:
You can't just pulled that up in a class. Just unclad without no method or a block.

And I thought, someone also mentioned it that you should initialize your class variables in your constructor. Which is a good practice.

Try the option I gave you and see what you have then let us talk about other part of your code.


I will use the option you gave, thanks, but I still want to know why the above code does not work. I don't really understand your explanation. If I create an object as an instance variable, shouldn't I be able to access it's contents from anywhere in that class? (using getters/setters for access).


praveen kumaar said:
You are not initializing the variables in your constructor rather you have a setter to do it,it is a very bad practice.


2) Is this always recommended? To initialize variables in the constructor? Also, if you do not use a constructor it is always recommended to initialize the variables as part of declaration? Also, I know if you don't provide a constructor Java will create one for you anyway but is it recommended to always provide a constructor as part of Java programming standard practice?

3) I'm not sure how to manage the creation of Car objects for the Reservation to be able to access them. The Reservation class needs to be able to know what cars are available from the inventory, and they will also need to display the specific Car object variables such as CarMake, CarModel, etc.
For example I will have to set multiple variable data for the car object for each car. Example:

Currently I have a Car class which every car will have an object, and I am creating the Car objects in the Reservation class. But I am thinking of creating a third class to sit in the middle called CarInventory. And I can move all the creation of the Car objects from the Reservation class to the CarInventory. But if I do that, then how can I access the Car object details (e.g CarID, CarModel, etc) from the Reservation class? Because the Reservation class will have one object of CarInventory and will not have direct access to the individual Car objects. In the Reservation class I cannot say: Can I?

Does Java have to have direct access to an object? I mean does the object declaration have to be in the same class that I want to access it? My example above in what I want to do is basically saying that I want to access Car object information from the Reservation class through/via the CarInventory class. Is that possible? If not then how should I be doing it?
---------------------------------------------------------------------------------------------------------------------------------------------

Hardik Jani said:
Right now I can not test your code but want to ask where is your Main class?


Main method is in the AutoRental class. See class diagram here: https://i.imgsafe.org/d8befede19.png
Most of my logic though is going to be in the Reservation class. Here I will have methods containing logic for:
SearchForCars
MakeReservation
EstimateReservation
SearchExistingBooking
ReturnCar
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:
1) I still do not understand why the following code does not work. The car1 object is created as an instance variable. So why can't I set the contents in the line below it?


To fully understand this, you'll need to dig into the Java Language Specification (JLS), which can be a daunting proposition even for seasoned programmers. If you are curious enough to try and follow that link, Scroll down to section 8.1 where you see a gray box with some italicised text in it. The relevant parts for you are what I show below:

The JLS wrote:ClassDeclaration:
...

NormalClassDeclaration:
... ClassBody


Then, click on the ClassBody link to follow it to the definition of a class body. Refer to that gray box and try to understand the following. This also shows the importance of properly formatting and aligning your code. Doing that will make it easier to see your program's structure and identify where its different parts start and end. Below is the code that you are having trouble with, reformatted so that it is properly indented and aligned. Compare this code's alignment with the alignment that you had.

Line 1 - This is what the JLS calls a ClassDeclaration. The "{" at the end of line 1 matches the first "{" in this definition:

ClassBody:
{ {ClassBodyDeclaration} }


The "}" on line 10 matches the last "}" in that definition. Everything else you've written between line 1 and line 10 matches the {ClassBodyDeclaration} part.

Line 4 - This is what the JLS calls an InstanceInitializer. Edit: See, I told you it can be difficult to follow; even I made a mistake at first. It's actually a ClassMemberDefinition! Specifically, it's a FieldDeclaration. You can follow that link and see that there are even more specifics to it.

Line 7 to 9 - This is what the JLS calls a MethodDeclaration

Line 5 - This is the line you are confused about. It does not match anything that the JLS lists as being something that can be contained in a legal ClassBodyDeclaration.

Now, since the Java Compiler has to follow and enforce the syntax rules laid out by the JLS as I just explained to you and there is no rule that the code on line 5 fits, this means that line 5 is illegal at that level in the code, therefore the compiler will tell you that it's not allowed.

If you follow the link to the details of the definition of an InstanceInitializer, then follow the link to the definition of Block, then keep figuring out what definition your code on line 5 fits and following the links for those, you will eventually get to the definition for Statement, then a few more links until you get to the definition for MethodInvocation, which is what line 5 is. (Another EDIT: this is actually misleading in a few ways, so let me just start over. Again, this shows how hard it can be to follow the JLS!)

If you follow the link to the details of the definition of an InstanceInitializer, then follow the link to the definition of Block, then Statement, then ExpressionStatement, then StatementExpression, then MethodInvocation, line 5 will match this definition under MethodInvocation:

ExpressionName . [TypeArguments] Identifier ( [ArgumentList] )

I will leave it to you to dig around those links to further definitions to figure out why that is so.

This ends our mini guided tour of the JLS for today.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:

You are not initializing the variables in your constructor rather you have a setter to do it,it is a very bad practice.


2) Is this always recommended? To initialize variables in the constructor? Also, if you do not use a constructor it is always recommended to initialize the variables as part of declaration? Also, I know if you don't provide a constructor Java will create one for you anyway but is it recommended to always provide a constructor as part of Java programming standard practice?


It's not necessarily "bad practice" per se. The answer to all those questions is: It all depends on the context. Always consider context.  

There are often cases where it is appropriate and even logical to have fields just take the default initial values that Java assigns them during object initialization if you don't explicitly assign a value in the field's declaration or in a constructor. It just depends on your design and the semantics of your object's use. You have to consider the different contexts in which new objects are created and determine whether it would be reasonable in some cases to have new objects with their default initial values.

Again, the JLS is the authoritative text to go to if you want to know what a particular field's default initial value will be. If you are feeling intrepid today, go to https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5 and try to understand what that section says.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:3) I'm not sure how to manage the creation of Car objects for the Reservation to be able to access them. The Reservation class needs to be able to know what cars are available from the inventory, and they will also need to display the specific Car object variables such as CarMake, CarModel, etc.


The various nuances to a full answer of this is what entire books about Object-Oriented Design and Analysis try to address. I emphasize "try" because there are an infinite number of possible routes you can choose in arriving at a design, some of which can lead to better results than many others. The trick to successful design is finding what those few options are that will give your design better longevity and other desirable -ities, like quality, reliability, maintainability, etc.  Since the possibilities are many and the specifics are dependent on the particular problem you are trying to address, no book can ever claim to be the be-all-and-end-all reference on OO Design and Analysis. The best any book can do is explain principles that you can follow to guide your decision making process and give you examples that you can try to follow and understand and relate to how those principles can be applied.

I will try give you another "brief" tour of OO Design as it pertains to this Car Reservation problem. Hopefully, this will give you an idea of just why programming and proper OO design is not an easy undertaking nor is it something that can be fully defined with a step-by-step list of instructions. Caveat: this is all off the top of my head and there are probably some things I say that others can and will shoot down as being "wrong" or "mistaken". That's fine.

The important thing to take away is that design is complicated and it's subject to interpretation, discussion, evaluation, and validation with an actual running program. Code that you can actually run will demonstrate how your design "ideas" translate to actual instructions that the computer will execute. Without an actual running program, everything you say or do is subject to debate. Running software, buggy or not, never lies. It always tells you "the truth" about the effectiveness and appropriateness of the decisions and choices you made during the design process. Sometimes that "truth" aligns with what you intended but more often than not, it doesn't. Again, there are many ways you can get to the "truth" that you desire but many more ways that lead you to saying things like, "Hey, that's not what I meant!"

So, with that in mind, let's start this mini design session tour! (See my next reply)
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:. . .  I plan to (later . . .

(Sorry for delay in replying; have been busy with gunpowder and trying to get prunings to burn in the rain. Both worked nicely, eventually )

Don't plan to do things later. Those are basic things which are the foundation of your program, and shou‍ld be done immediately. Those things which will take two minutes to sort out now will cost you hours of work if left till later. Get the design of your class working first, and you will then have to make the design of your other classes right. When you have done that, you will have a correctly‑designed application. It isn't some sort of punishment, but something correctly‑designed. You will then actually find it quite simple to add serialisation. It might take time to work out if you haven't used serialisation before, but it will be simple when it works.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:3) I'm not sure how to manage the creation of Car objects for the Reservation to be able to access them. The Reservation class needs to be able to know what cars are available from the inventory, and they will also need to display the specific Car object variables such as CarMake, CarModel, etc.



See my previous reply for caveats that apply to this reply.

Does a Reservation really need to "know what cars are available from the inventory"? Maybe the job of "knowing" what Cars are in inventory is more appropriately assigned to an Inventory object. Then a Reservation object just needs to know what Inventory object it needs to ask "Hey, do you have this kind of Car available in stock?" What would the code for that look like? Maybe the following?

What that "@Inject" on line 3 does/means is beyond the scope of this reply. Ask about that in another thread or just go Google for examples of how that works.

Does a Reservation really need to "display a specific Car's make, model, etc."? Or should you think about it in terms of asking some other class to display the detailed information of a given Car object? That way, a Reservation object doesn't need to even care about how a Car's details are displayed and instead focus on things that a Reservation object can be reasonably expected to care about. What would the code look like for that if we went with that line of reasoning? Maybe this:

The design principles/techniques involved in making these kinds of decisions about how a Reservation object would behave include Separation of Concerns, Encapsulation, Dependency Injection and Abstraction to name just a few off the top of my head.

So you see, there are a lot of things you need to learn about how you to make good design decisions and get an idea of why people are asking you about why you did this thing or that thing.

This concludes today's mini tour of the Design Process.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:
Most of my logic though is going to be in the Reservation class. Here I will have methods containing logic for:
SearchForCars
MakeReservation
EstimateReservation
SearchExistingBooking
ReturnCar


Ok, let's do a short extended tour of the Design Process.

Should a Reservation be responsible for searching for Cars or should an object like Inventory do that?

Should a Reservation search for existing Bookings or should it delegate that job to a BookingRepository object?

Should a Reservation be responsible for doing the things we intend to do in "ReturnCar"? Or should a Reservation object just tell an Inventory object that the Car associated with that Reservation has been returned? The code might look something like this: inventory.return(this.car), where this.car refers to the Car that's associated with this particular Reservation.

The name "MakeReservation" seems like a no-brainer (duh!). Is there another name that's more expressive of what we intend to do in this method? Did we really mean "saveReservation"? "createReservation"? "confirmReservation"? Or are the tasks involved in making a reservation something that should be coordinated by another class, like a BookingService class maybe? Maybe the BookingService class will be the "manager" that coordinates the overall booking/reservation process and then it just delegates certain subtasks in that process to a Reservation object while it delegates other tasks to other related objects, like Inventory and Accounts Receivable, and Billing, and CustomerLoyaltyTracking, and ... so on and so forth.

These are just a few questions you can ask to discover alternative choices you can make for the design of your program.
 
Graham Sills
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Junilu Lacar


Line 5 - This is the line you are confused about. It does not match anything that the JLS lists as being something that can be contained in a legal ClassBodyDeclaration.


This doesn't make sense to me because there are many things than can be done in a class body apart from 'ClassBodyDeclaration'. Line 5 is not part of ClassBodyDeclaration,I know, and I'm not trying to declare anything in line 5. That is already in line 4. Line 5 is invoking a method but are you telling me Java does not allow invoking a method if it is not stated within another method?

I have spent some time in the JLS and it's not very informative for a beginner, quite convoluted.

Can someone try explain to me in layman's terms why line 5 is not allowed?


3) I'm not sure how to manage the creation of Car objects for the Reservation to be able to access them. The Reservation class needs to be able to know what cars are available from the inventory, and they will also need to display the specific Car object variables such as CarMake, CarModel, etc.
For example I will have to set multiple variable data for the car object for each car. Example:

Currently I have a Car class which every car will have an object, and I am creating the Car objects in the Reservation class. But I am thinking of creating a third class to sit in the middle called CarInventory. And I can move all the creation of the Car objects from the Reservation class to the CarInventory. But if I do that, then how can I access the Car object details (e.g CarID, CarModel, etc) from the Reservation class? Because the Reservation class will have one object of CarInventory and will not have direct access to the individual Car objects. In the Reservation class I cannot say:
?
1
CarInventoryInstance.Car1.getCarType()
Can I?

Does Java have to have direct access to an object? I mean does the object declaration have to be in the same class that I want to access it? My example above in what I want to do is basically saying that I want to access Car object information from the Reservation class through/via the CarInventory class. Is that possible? If not then how should I be doing it?



Can someone address this specifically? I understand there are probably multiple ways of doing this but I am new to Java. I don't need a "perfect" way of doing it. If someone can offer one or two of the most logic ways that I can do this then let me know.


Junilu Lacar asks:
Does a Reservation really need to "know what cars are available from the inventory"?


Yes because I want the reservation search to find out what is available, and then display some of the car attributes to the screen, e.g carMake, carModel, regNumber, etc.

---------------------------------------------------------------------------------------------------------------------------


Campbell Ritchie wrote:
Don't plan to do things later



I agree with this if you have the tools and capabilities. But I don't. As I said I am new to Java. This is an incremental activity. I'll be building this project ugly to begin with, I just want it to work initially, taking on one thing at a time, constantly learning, & then to improve it & incorporate better programming/techniques. If I try to plan everything and make everything efficient/proper from the beginning then I will never get this project working and it will just be too overwhelming. I don't want to take on a mammoth, I'm doing this in bite-size/manageable chunks.
 
Henry Wong
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:


Line 5 - This is the line you are confused about. It does not match anything that the JLS lists as being something that can be contained in a legal ClassBodyDeclaration.


This doesn't make sense to me because there are many things than can be done in a class body apart from 'ClassBodyDeclaration'. Line 5 is not part of ClassBodyDeclaration,I know, and I'm not trying to declare anything in line 5. That is already in line 4. Line 5 is invoking a method but are you telling me Java does not allow invoking a method if it is not stated within another method?

I have spent some time in the JLS and it's not very informative for a beginner, quite convoluted.

Can someone try explain to me in layman's terms why line 5 is not allowed?



Java statements that are not declarations must be in constructors, methods, or initializers. The Java Language Specification defines the syntax of the language, and what it means. So, with declarations, and with statements (in constructors, methods, initializers), it is valid -- and the compiler know what to do (in terms of generating code) for them.

Anyway, let's reverse the question. Let's assume that line 5 is allowed, when should line 5 execute? meaning what code should the compiler generate for it? ... perhaps, if we understood what you expect to happen, then we can provide the valid syntax for it.

Henry
 
Graham Sills
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And this only applies to objects? Because for primitive types it is possible to use various expressions and statements.

Is there anything apart from object declarations that IS allowed for object reference types (outside of methods)?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:And this only applies to objects? Because for primitive types it is possible to use various expressions and statements.

Is there anything apart from object declarations that IS allowed for object reference types (outside of methods)?


The same kind of rules that apply to objects and reference types apply to primitive types as well. No, you cannot use various expressions and statements. There is a very limited number of things you can do outside of a method or initialization block that will result in code being executed. For the most part, statements like your line 5 MUST be inside some kind of block of code that's delimited by a pair of open-closed braces "{ ... }" that doesn't belong to a class declaration.

I gave you fair warning that the JLS can be difficult to follow but asking for explanations in layman's terms has the potential of reducing the conversation to oversimplifications that may still not give you the depth of understanding that you are searching for. You can't explain how a transmission works to your mom and expect her to be able troubleshoot any problems with it if you just tell her in "layman's terms," right? You have to get her into a pair of old clothes and actually root around under the hood and she needs to have a certain level of mechanical aptitude and understanding to get it. If you really want to understand what's going on with that line, roll up your sleeves and learn the syntax. You may think it's too much to ask a beginner to wade through the syntax diagrams in the JLS but honestly, that's how I learned the syntax as a beginner. And if you really want to know and you can't understand it just yet, I'd advise that you let it go for now, just follow the rules, and come back to it later when you have a broader sense of how Java works.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Graham Sills wrote:

Line 5 - This is the line you are confused about. It does not match anything that the JLS lists as being something that can be contained in a legal ClassBodyDeclaration.


This doesn't make sense to me because there are many things than can be done in a class body apart from 'ClassBodyDeclaration'. Line 5 is not part of ClassBodyDeclaration,I know,


That is incorrect. You have misunderstood the syntax definition. The definition of "ClassBodyDeclaration" that I referenced is like saying "Everything that's below your neck and above your hips is your "Torso".  The definitions in the JLS are hierarchical, meaning they go from the big thing, "ClassBodyDeclaration" and break it down into its next level of component parts, which includes only the four things listed under it as shown here: https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-ClassBody

Think of those definitions like an animated exploded diagram of the parts of a car. The ClassBodyDeclaration is the whole car, all assembled together. At the next level of explosion, you separate the car into it's major parts: you'll have the Body, Engine, Frame/Undercarriage, and perhaps the Exhaust system, the Fuel system, and the Electrical system as the smaller subassemblies.  Your line 5 is like trying to put a spark plug at this level of the diagram. A spark plug doesn't belong at this level. It belongs at a smaller level of detail, after you've done more progressive explosions of components of subassemblies of subassemblies.

Line 5 can be eventually found to be a legal part of three out of four of those direct "subassemblies" of ClassBodyDeclaration, the lone exception being that of a StaticInitializerBlock. Since car1 is a reference variable declared as an instance member (line 4 qualifies as a ClassMemberDeclaration, specifically, a FieldDeclaration, as I mentioned previously), a StaticInitializerBlock cannot contain any direct reference to it.

I don't know how to explain this in any simpler, "layman's terms" because no ordinary layman who doesn't understand how compilers work has any hope of understanding this. Understanding this requires you to rise above the level of "layman", IMO.
 
Ranch Hand
Posts: 109
2
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'll explain this in layman terms (but I'm not a programmer). If you create a class and you want to have a command or manipulation of a specific created object, you will need to place that into either a constructor or method...anything outside of that will simply not run, thus it will simply not exist. And it's illegal and apparently it's illegal not to exist in Java
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sergiu Dobozi wrote:I'll explain this in layman terms (but I'm not a programmer). If you create a class and you want to have a command or manipulation of a specific created object, you will need to place that into either a constructor or method...anything outside of that will simply not run, thus it will simply not exist. And it's illegal and apparently it's illegal not to exist in Java



Good try.

However, you left out line 5 being legal in an instance initializer block. Besides, in this context, "class", "object", "constructor", and "method" are hardly layman's terms, if you ask me.
 
Sergiu Dobozi
Ranch Hand
Posts: 109
2
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Good try.

However, you left out line 5 being legal in an instance initializer block. Besides, in this context, "class", "object", "constructor", and "method" are hardly layman's terms, if you ask me.



Yes, you're right But I think we also left out static initialization blocks, no?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sergiu Dobozi wrote:But I think we also left out static initialization blocks, no?


I already mentioned that car1 that is declared on line 4 as an instance field, cannot be referenced from inside a static initialization block.
 
Anderson gave himself the promotion. So I gave myself this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic