Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

method in subclass not seeing method in abstract superclass

 
Bud Tippins
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following code in the main.java file.



In the abstract Fruit class I have:



Why am I getting an errot on the "myApple.sayFruit();". Isn't the sayFruit() method visible to main?

Thank you.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12185
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is that all your code? Your main() method has to be inside a class, which it does not appear to be from what you posted. I put this in a file called "Tester.java"

and this in another file called Fruit.java

I compiled both files, and it ran just fine:

C:\slop>java Tester
I'm gonna call apple
I'm an apple
I'm a fruit


 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You've defined your sayFruit() method with the package-private modifier (i.e. you've not used an access modifier like public, private or protected for it) so visibility for it is classes in the same package as your Apple class. Sub classes cannot see it unless they are in the same package too.



 
Bud Tippins
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry. Here is the complete code in Main.java:



This is in fruit.java:



Thank you for your help
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's because you haven't added an access modifier to sayFruit. And by default it gets package access, which means that it's only accessible to classes in the same package - which doesn't include Main. Add public and it will work.

Edit: sorry - missed that Paul had already said that.
 
Bud Tippins
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you. That worked.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic