Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Thinking in java Package excercise  RSS feed

 
Sami Devine
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(1) Create a class in a package. Create an instance of your class outside of that package.

I have created the following two programs



The above code I placed inside a folder called Apple and compiled it.



I think this is the expected solution but I have not used the import statement for the package. Is this correct? Have I created a package at all?
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it work? Does it compile? Does it run?

What you are doing is using the fully qualified names of the classes, which is entirely correct. There is only one tiny mistake: if you look here, you find package names are all lower-case. So the package should be called apple, rather than Apple.
 
Sami Devine
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Campbell
yes it works, which is why I wondered why an import statement is not needed
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16027
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It works because in line 3 of your second piece of code you are referring to class Pear by its fully-qualified class name: Apple.Pear (package name, dot, class name).

An import statement is only a way to avoid typing long fully-qualified classnames all the time. You could have written this:

So, "import Apple.Pear" just means "if I write Pear, I actually mean Apple.Pear, or class Pear in package Apple". Instead of importing it, you also just write the package name explicitly everywhere you use it.
 
Sami Devine
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper,Campbell thanks, I worked out another example using import statements and it worked fine. I have understood this part.
Package 1:


Package 2:





 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16027
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, do you still have a question?

In your last example you have two classes both named Deb1, but in different packages. In the last piece of code you can choose which one of these two to use by either importing Deb1 from the package debug or the other Deb1 from the package debugoff.
 
Campbell Ritchie
Marshal
Posts: 55681
162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you can use both classes, but you must refer to them by their fully qualified names.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!