Hi, I just had a question regarding this task:
I had an error when I was posting the solution like this:
public class Solution {
public static void main(String[] args) {
Cat cat = new Cat();
cat.owner = woman;
Dog dog = new Dog();
dog.owner = woman;
Fish fish = new Fish();
fish.owner = woman;
Woman woman = new Woman();
But when I arranged it like this it was correct. The part when I set the owner to woman only worked when it was placed AFTER the created objects.
public class Solution {
public static void main(String[] args) {
Cat cat = new Cat();
Dog dog = new Dog();
Fish fish = new Fish();
Woman woman = new Woman();
cat.owner = woman;
dog.owner = woman;
fish.owner = woman;
Can this code be ordered a different way? Or only in the second example?
Is it possible to write it like this with a space in between the animals? I can't check anymore because I've already solved it.
Cat cat = new Cat();
cat.owner = woman;
Dog dog = new Dog();
dog.owner = woman;
Fish fish = new Fish();
fish.owner = woman;
Woman woman = new Woman();
Just wondering if I missed any details about placement of the lines... thanks.
hidden #10484120
Level 13
Does it matter the order of the lines?
Resolved
Comments (6)
- Popular
- New
- Old
You must be signed in to leave a comment
Shubham Sharma
14 July 2019, 08:03
you have to declare the woman object first and after that order n space doesn`t matter.
0
Yvonne
13 July 2019, 20:24solution
Because a class is a blueprint of an Object, it needs to be built/created in order to be used. And we build it by Instantiation (i.e Woman woman = new Woman ()). So if we don't instantiate an object first, then using it's properties (i.e. owner property -> fish. owner... etc.) would be impossible; almost like it doesn't even exist.
In other words If you want to invoke the methods of local inner class you must instantiate this class,
and basically that's why having Woman woman = new Woman() object created first before using its property i.e cat.owner ,is important.
The spaces don't really matter depends on how you want your code to look spaghetti or readable.
Hope it helps.
+4
hidden #10484120
13 July 2019, 21:02
Thank you, this is really helpful. Do you have any recommendations of a book, youtube channel that has really nice answers like yours? :)
0
Yvonne
15 July 2019, 01:20
Javatpoint site has really helped me a lot, it has detailed explanation with examples for each, check it out. Book--> Head first Java did it all.
+1
hidden #10484120
15 July 2019, 08:49
You're amazing, thanks!
0
Dmitriy Bursa
13 July 2019, 19:48
in your first variant:
you assign owner of cat before create him.
in this variant you need string
to insert first.
You can create objects in any order, but you can only access them if they have already been created.
spaces for easy code reading :) 0