• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why Compiler error?.....

 
tvs sundaram
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This class doesn't compile.
I thought that in Line 1
Process t = new TestA(); //1
we are creating an object of type TestA which has class reference as Process.. that's causing the error.
I tried to change Line //1 as
Process t = new Process();
But still I get the same error.
Error message is
"No method matching write() found in class Process.
I haven't understood the flow of the program. Is it anything related with the access modifier private.. Can somebody explain pls..
Thanks in advance.
-------------------------------------------
Code
<ubb>
class Process
{
String s="Java";
Process()
{
write();
}
private void write()
{
System.out.println(Thread.activeCount());
}
}
class TestA extends Process
{
String s="JavaScript";
public static void main(String[] args)
{
Process t = new TestA(); //1
t.write();
System.out.println(t.s);
}
public void write()
{
System.out.println(Thread.interrupted());
}
}
</ubb>
-----------------------------
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that TestA cannot access Process.write(). The access modifier private means that only Process objects can access that method. There are two ways to fix it. First, you can change Process.write to any other access modifier at all (public, protected, and default/package). Since TestA is both a subclass and in the same package, it would be allowed to access the method. The other option is to store/cast 't' as/to a TestA object, where write can be accessed by main().
Process t = new TestA(); //1
((TestA) t).write();
System.out.println(t.s);
or
TestA t = new TestA(); //1
t.write();
System.out.println(t.s);
or
private void write() -> public/protected/nothing void write()
[This message has been edited by David Garland (edited August 12, 2001).]
 
Cameron Park
Ranch Hand
Posts: 371
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I always thought what methods are available is determined by the actual object type. For instance,
Object object = new String("Hi!");
object.toString() will return "Hi!" and not some hashing mumble jumbles. But here it seems like it is also determined by the reference type. Can someone shed some light on as to what are determined by the actual object type and what are determined by the reference type?
Thanks.
 
Alex Sbityakov
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cameron,
private methods do not particiate in inheritance, because the are invisible to the subclasses. This is precisely why, the program says that it can't find method write() in class Process - it is simply invisible to everything outside the class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic