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

"protected" error

 
newtojava
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:
Could anyone pls explain why I'm getting the following error.
My classpath is set to : .;G:\CorejavaBook
Then I created a package under G:\Corejavabook\Corejava --->
package corejava;
public class myclass
{
public myclass()
{
System.out.println("New Object of myclass:" );
}
protected void bite()
{
System.out.println(" In bite");
}
}
When I write the following Class to access the Protected func--->
import corejava.*;
public class cake extends myclass{
public cake()
{
System.out.println("cake constructor");
}
public static void main(String[] args)
{
myclass x = new myclass();
x.bite();
}
}
I get a error "Can't access protected method bite".I'm new to Java, could you pls explain why can't I access the protected method. From what is in the book, protected is accessible in subclass in other packages.
Thanks in advance.
newtojava
 
Lancy Mendonca
Ranch Hand
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class that you have created is an instance of myClass. In myClass protected is equivalent to a private object. Hence you cannot access it.
if your code read
public static void main(String[] args)
{
cake c = new Cake();
c.bite(); // It will work.
//However the following will compiler error
MyClass m = new MyClass();
m.bite();
// Or
MyClass m = new Cake();
m.bite();
This is surely a tricky thing to understand for a beginner. If U need more explaination I will be happy to explain further.
}
 
bill bozeman
Ranch Hand
Posts: 1070
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A further explanation would be great. There seems to be many questions on this matter lately. Also when it comes to packages and classpaths and when and where problems will arise. I thought I understood it ok, but when I tried looking at some of these issues, I got more confused.
Thanks
 
newtojava
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Lancy
Thanks for the reply.Could you pls explain some more on this topic.This is educational and more helpful than reading a book.
Thanks a lot in advance.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic