This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can't access finalize() method !!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can Watch "can New topic
Author

can't access finalize() method !!!

vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Hi All,
I compiled the follwing code and it gave 3 errors.
CODE
-----
<pre>

public class ObjectClassTest
{
public static void main(String s[])
{
Object o = new Object();

System.out.println("o.finalize() : " + o.finalize());
}
}

</pre>
---------
END OF CODE
The erros were :
1)ObjectClassTest.java:13: Incompatible type for +. Can't convert java.lang.String
to int.
System.out.println("o.finalize() : " + o.finalize());
^
2)ObjectClassTest.java:13: Incompatible type for +. Can't convert void to int.
System.out.println("o.finalize() : " + o.finalize());
^
3)ObjectClassTest.java:13: Can't access protected method finalize in class java.la
ng.Object. java.lang.Object is not a subclass of the current class.
System.out.println("o.finalize() : " + o.finalize());
^
3 errors
-----------
I understood the error 2. But what about error 1) and 3).
I'm confused with 1) and I can't understand why I can't access
finalize() from my class (error 3)).
Could anyone explain me ?

------------------
Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************


Regards<BR>---------<BR>vadiraj<P><BR>*****************<BR>There's a lot of I in J.<BR>*****************
Cherry Mathew
Ranch Hand

Joined: Dec 26, 2000
Posts: 159
u cant access a protected method from another class which is not the subclass of that. if u r not convinced then just think of calling a private variable from another class using the object refernece. Object is in another package and protected acts like private in other package classes which is not subclass of that.
vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Hi Cherry,
Thanks for your reply.
u cant access a protected method from another class which is not the subclass of that.

I agree with your point. But regarding the access specifiers,
I know that protected is less restrictive than the package level accessability(no access specifier).
I know one more fact that the java.lang package which contains the Object class among ohter useful classes, is imported
automatically by the compiler.
I would like to mention one more fach that Object class is the superclass of all other classes.
So why is the error 3)?
Could you throw some more light on this?

------------------
Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************
vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Could someone help me?
This is to George,Bill,Paul and moderators.
Thanks,
vadiraj
Cherry Mathew
Ranch Hand

Joined: Dec 26, 2000
Posts: 159
i agree with u that Object is the super class of all classes so finalize should be available.
someone please clarify
George Toronto
Ranch Hand

Joined: Dec 30, 2000
Posts: 78
Hi,Vadiraj
Honestly, you really stuck me. At first, I think it is easy to answer, but when I wrote more and thought there was not so easy to answer.
First, I will clarify the Cherry Mathew's statement. A class' protected methods can be accessed by the its subclass and other classes in the SAME package.
This point is different with C++. So care should be excercised.
Secondly, I check you code and sure the compile errors appear since I think finalize() method is my weak point and am not sure there is error about it( i mean to call finalize()). If you call a subclass's finalize() method which you should implement youself, everything is OK. Then I analyized the heriarchy relationship and OOP concepts, but I couldnot find certain answer. Is there a trick about JAVA just like String.concat("")?Moreover, I think finalized() should be called implicitly by GC rather than we call it explicitly.
I sorry about that, and I should read more materials.
Can anyone help us? Hi, Mapraputa Is, Jane Griscti, Angela Poynton, bill bozeman, Maha Anna and other friends can help me ?
regds
George
vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Hi George,
Thanks for your comment.
I modified my code and I saw that I can call finalize() of Object class from
my class within a non-static method.
Now is that am I doing wrong by constructing obejct on Object class?
But still it should work, since we can create an object on any class
that we created and access its finalize() method.
The code below is what I tried.
CODE
-----
<pre>

class MyClass
{
protected void finalize() throws Throwable
{
System.out.println("Hi, Java is amazing language !!");
}
}
public class FinalizeTest
{
public static void main(String s[]) throws Throwable
{
MyClass m = new MyClass();
m.finalize();
}
}
OUTPUT :
Hi, Java is amazing language !!

</pre>
-----------
END OF CODE
Now is that the same thing I'm doing in my code?
I don't able to understand why?

Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************
[This message has been edited by vadiraj vd (edited January 05, 2001).]
Vladimir Kositsky
Ranch Hand

Joined: Nov 03, 2000
Posts: 116
I suspect that finalize() cannot be called explicitely. Just GC can call finalize() on object eligible for garbage collection.
But at least you can try override it
sunilkumar ssuparasmul
Ranch Hand

Joined: Dec 13, 2000
Posts: 142
coming on to similar question the below class compiles and runs successfully even though the method finalize and hashCode are not defined? but how is taht the Object class methos r still accessible even though it is overridden. I am totally confused PLZ throe some light?

class ObjectClassTest {
}
public class Object extends ObjectClassTest {
public static void main(String s[])throws Throwable {
Object o = new Object();
o.finalize();
System.out.println("hashcode"+o.hashCode());
}
}


"Winners don't do different things<br /> They do things differently"
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
Very interesting( and misleading? ) discussion indeed.
Firstly dont get misled by <code>finalize()</code> method. There is no mystery to this behaviour. You will get the same error "can't access protected method....." if you were to replace the call to <code>finalize()</code> with call to another protected method in <code>Object</code> class, say <code>clone()</code>
Since it is clear that the reason for this error is the 'protected' access, lets talk about the this access specifier. The access level specifier protected, allows the class itself, subclasses , and all classes in the same package to access the members. The important thing to remember is the package restriction. If you're outside the package that declares the protected entity, you cannot access it!
Now lets look at your code. Clearly all the classes we have written so far have no <code>package</code> statement and hence they all belong to the 'default' package. If you have read the Java API documentation, the <code>Object</code> class is defined in the <code>java.lang package</code>. That is the reason for the error!. How can you access the <code>protected void Object.finalize()</code> outside the package? It is illegal and compiler knows it
Having said that, if you want to make your code compile, you have to cheat the compiler. Take a look at the following code

The code has two changes, both marked in Blue. I included the package statement to make the compiler think this class belongs to the same package that defines the <code>Object</code> class. This is all that is required to satisfy the compiler. The second change is the throws clause which is required because the finalize method throws an instance of Throwable.
If you do these changes and compile the code, Voila! it compiles and works fine!!
Lastly, I feel obligated to clear some myths about the <code>finalize()</code> method because I see there is a lot of confusion about it. A finalizer can be invoked explicitly, just like any other method. Read more in JLS Section 12.6 Finalization of Class Instances. If the finalize method is called explicitly, it will just get executed as another method and will not result in the object being GC'd.
sunilkumar, the hashcode is a public method defined in the <code>Object</code> class. You can access it in any other class because all classes inherit from the <code>Object</code> class. You don't have to override it inorder to access it!.
Phew!! This answer turned out to be longer than I thought. However I hope it has cleared the confusion.
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
Dear Ajith:
The access level specifier protected, allows the class itself, subclasses, and all classes in the same package to access the members. The important thing to remember is the package restriction.
According to the above point, the protected modifier will be exactly like the default package access modifier(the friendly nothing). But as Bill Brodgen's exam cram and other books told us:
A protected member can be access only by classes in the same package and classes derived from the current class- no matter which package they are in. Exam Cram P62 in my version
It is widely recognized that default access is more restrictive than the protected modifier, because protected member can be accessed by subclasses outside the package.
But now I'm really confusd. My computer has problem accessing other packages because I messed around with the classpath. Can someone try some examples and clarify more?


Sun Certified Java Programmer
Vladimir Kositsky
Ranch Hand

Joined: Nov 03, 2000
Posts: 116
Ajith,
If extends clause does not used, class extends java.lang.Object implicitely, that , for my opinion, should be enough to access protected method of parent class Object.
JavaTM 2 Platform
Std. Ed. v1.3
finalize() - Method in class java.lang.Object
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

JLS
20.1.11 protected void finalize() throws Throwable
The general contract of finalize is that it is invoked if and when the Java Virtual
Machine has determined that there is no longer any means by which this object can be
accessed by any thread that has not yet died (�12.7), except as a result of an action taken by the finalization of some other object or class which is ready to be finalized.

[This message has been edited by Vladimir Kositsky (edited January 05, 2001).]
[This message has been edited by Vladimir Kositsky (edited January 05, 2001).]
vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Hi ajith and others,
Thanks for your valuable response.
Ajith I understood the concept of protected modifier.
I would like to raise the same fact pointed by Vladimir Kositsky
that,
all classes are sub classes of java.lang.Object class directly or indirectly.
So having protected midifier should not prevent us from accessing the finalize() method as our class is by default
sub class of the Object class.

Ajith could you throw some more light in this direction?
Thanks everyone again,


------------------
Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************
vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Hi All,
I found one more thread discussing same topic.
There the example given by Randall Twede. He does exactly same thing but he says it is correct.
I didn't get it.

------------------
Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
Hi, everyone:
After testing some programs and looking up a lot of books, I believe I know where the real problems lie. Ajith is right, the biggest problem is the understanding of the protected modifier. It's not as simple as I have thought. Even Ajith's explanation is somewhat misleading(sorry Ajith, you are almost right everytime except this one). The most precise defination I found so far is as follows:
'protected' means all classes in the same package (like default) and sub-classes in any package can access the features. But a subclass in another package can access the protected members in the super-class via only the references of subclass or its subclasses. A subclass in the same package doesn't have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.

Vadirag, for you first example, you are trying to invoke the protected method finalize using the superclass reference Object o, therefore the compiler gives error message as follows:
Can't access protected method finalize in class java.lang.Object. java.lang.Object is not a subclass of the current class.

However you can invoke the finalize method with a reference of the class ObjectClassTest or its subclass. but since every class inherits the finalize method from the ultimate superclass Object, that doesn't look very useful.
Hope this helps.
Tom

Cherry Mathew
Ranch Hand

Joined: Dec 26, 2000
Posts: 159
Hi Tom
i agree with what u wrote the problem lies in the understanding of protected modifier
im writing what i understood about this please correct me if im wrong.
protected acts like public in the same package and acts like private in other package with the exception that subclasses has got access to it.
<qoute>
'A subclass in another package can access the protected members in the super-class via only the references of subclass or its subclasses . A subclass in the same package doesn't have this restriction. This ensures that classes from other packages are accessing only the members that are part of their inheritance hierarchy.</Qoute>
but i didnt get these lines of the explanation u gave. subclasses or its subclasses and again how will this help ensure that other classes accessing it is in the inheritance hieraarchy.
i got a vague idea about what u mean but pelase explain it to me in deatail
Cherry
Vladimir Kositsky
Ranch Hand

Joined: Nov 03, 2000
Posts: 116
To invoke non-static member you must create an instance of class where member is defined. Member have to be visible (accessible).
MyClass m = new MyClass();
m.finalize();
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
Consider the following code:

In the above example, you are using the subclass reference tt to call the finalize method of Object class.
Tom Tang
Ranch Hand

Joined: Dec 24, 2000
Posts: 133
And you can also do the following thing.
[code]
public class ObjectClassTest
{
public static void main(String s[]) throws Throwable
{
Object o = new Object();

o.finalize();//You are calling the finalize method with a subclass reference o. Object class has been redefined and finalize method overidden
}
}
class Object extends ObjectClassTest{
protected void finalize(){
System.out.println("Java actually makes sense");
}
}
Hi, Cherry, I think the rule I quoted is just part of Java's protection mechanism against tampering with source code. I believe in real life coding, we are just using public and private a lot. You either get it all or nothing.
Rosemol Thanjappan
Ranch Hand

Joined: Aug 08, 2000
Posts: 40
Hi,
this is what The JavaTM Tutorial says
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html


Protected
The access level specifier protected, which allows the class itself,
subclasses , and all classes in the same package to access the
members. Use the protected access level when it's appropriate
for a class's subclasses to have access to the member, but not
unrelated classes. Protected members are like family secrets--
you don't mind if the whole family knows, and even a few trusted
friends but you wouldn't want any outsiders to know.
To declare a protected member, use the keyword protected.
First, let's look at how the protected specifier affects
access for classes in the same package.
Consider this version of the Alpha class which is now declared
to be within a package named Greek and which has one protected member
variable and one protected method declared in it:
package Greek;
public class Alpha {
protected int iamprotected;
protected void protectedMethod() {
System.out.println("protectedMethod");
}
}
Now, suppose that the class Gamma was also declared to be a member
of the Greek package (and is not a subclass of Alpha). The Gamma class
can legally access an Alpha object's iamprotected member variable
and can legally invoke its protectedMethod:
package Greek;
class Gamma {
void accessMethod() {
Alpha a = new Alpha();
a.iamprotected = 10; // legal
a.protectedMethod(); // legal
}
}

That's pretty straightforward. Now, let's investigate how the
protected specifier affects access for subclasses of Alpha.
Let's introduce a new class, Delta, that derives from Alpha
but lives in a different package--Latin.
The Delta class can access both iamprotected and
protectedMethod, but only on objects of type Delta or its subclasses.

The Delta class cannot access iamprotected or protectedMethod
on objects of type Alpha. accessMethod in the following code
sample attempts to access the iamprotected member variable on
an object of type Alpha, which is illegal, and on an object of
type Delta, which is legal. Similarly, accessMethod attempts
to invoke an Alpha object's protectedMethod which is also illegal:
package Latin;
import Greek.*;
class Delta extends Alpha {
void accessMethod(Alpha a, Delta d) {
a.iamprotected = 10; // illegal
d.iamprotected = 10; // legal
a.protectedMethod(); // illegal
d.protectedMethod(); // legal
}
}
If a class is both a subclass of and in the same package as
the class with the protected member, then the class has access
to the protected member.


This is the explanation and so
we can't access the protected methods of Object class on
an instance of Object where it is declared .It is
only accessible through the subclasses of Object, if the
current class is in a different package.
So the rules to remember are:
Rule 1:
If a class is both a subclass of and in the same package as
the class with the protected member, then the class has access
to the protected member.


Rule 2:
If a class is a subclass of and not in same package as
the class with the protected member, then the class has access
to the protected member but only on objects of type , its subclasses.


Rule 3:
If a class is not a subclass of and in same package as the class
with the protected member ,then the class has access to the
protected member.


Hoping this may help......
Rosemol

[This message has been edited by Rosemol Thanjappan (edited January 06, 2001).]
Rosemol Thanjappan
Ranch Hand

Joined: Aug 08, 2000
Posts: 40
Hi,
This is just an addition to the previous post.
Rule 2:
If a class is a subclass of and not in same package as
the class with the protected member, then the class has access
to the protected member but only on objects of type , its subclasses.

its subclass is not the subclass of class with protected member in the same package itself .
It must be the subclass of current class accessing the protected
member ,in this different package.

Consider this.:
In package 'Flower'
public classes 'Rose' and 'WhiteRose'(subclass od Rose).

In default package

public class 'Test' (subclass of Rose).

and in the same package Flower

and in default package

Hoping this may help......
Rosemol

saumil shukla
Ranch Hand

Joined: Dec 01, 2000
Posts: 47
one more interesting thing, Protected modifier deepends up on
the reference type and not on the Object Type.
[code]
public class ObjectClassTest {
public static void main(String s[])
{
ObjectClassTest o = new ObjectClassTest();
Object o1 = new ObjectClassTest();

try{
System.out.println("o.finalize() : " );
o.finalize();
o1.finalize();
}
catch (Throwable e)
{
System.out.println("Exception in Finalize");
}
}
}
the compiler shoust for o1.finalize() and not for o.finalize();
Thanks
srinath choudhary
Greenhorn

Joined: Jan 06, 2001
Posts: 3
It was a very interesting Discussion . It cleared some of my misconceptions about private access modifier.
I think other moderators must have posted their reply.
Ajith is nice.but his concept was really little bit confusing
sreenu
vadiraj vd
Ranch Hand

Joined: Dec 15, 2000
Posts: 68
Thanks everyone,
Now I can say, I clearly understood what is meant by protected.
I tried an example below to check out Tom's explaination.
Here I created two classes in different package.
MyClassUsedinFinalizeTest is in package p.pack and FinalizeTest is in the package p.
The compiler gave the following error.
FinalizeTest.java:10: No method matching meth() found in class
p.pack.MyClassUsedInFinalizeTest.
m.meth();
^
1 error
Here's the code
CODE
-------
<pre>

// filename MyClassUsedInFinalizeTest.java in p.pack.
package p.pack;
public class MyClassUsedInFinalizeTest
{
protected void meth()
{
System.out.println("Hi, Java is amazing language !!");
}
}
// filename FinalizeTest.java in p.
package p;
import p.pack.*;
public class FinalizeTest
{
public static void main(String s[])
{
MyClassUsedInFinalizeTest m = new MyClassUsedInFinalizeTest();
m.meth();
}
}

</pre>
----------
END OF CODE
the command I used to run is -
<pre>d:\java>javac -d . MyClassUsedInFinalizeTest.java <enter>
d:\java>dir d:\java\p\pack <enter>
MyClassUsedInFinalizeTest.class
d:\java>javac -d . FinalizeTest.java <enter>
FinalizeTest.java:10: No method matching meth() found in class
p.pack.MyClassUsedInFinalizeTest.
m.meth();
^
1 error
</pre>
Correct me if I'm wrong.
Thanks again for an interresting discussion.


------------------
Regards
---------
vadiraj

*****************
There's a lot of I in J.
*****************
Kalpesh Soni
Ranch Hand

Joined: Jan 02, 2001
Posts: 312
hi guys
i just wanted to tell you all one thing
if you write this code :

what i mean is
if you make an object of Object and use a reference of Object
you cannot call finalize()
so when you assign the derived class object to a base class reference
Object o1 = new ObjectTest()
the compiler is not smart enough to know whether the reference o has object of Object class or ObjectTest class
and it will prevent you to say
o1.finalize() just the same way it says no to o2.finalize()
because finalize is protected and you cannot access it outside java.lang package directly
but when you use derived class reference everything is fine
i think this will help


------------------
KS


Test 094, IBM WID 6.0 cert
SCJP 1.2
SCBCD 1.3 Beta
SCWCD 1.4 Beta
SCMAD Beta
SCDJWS Beta

KS
Rosemol Thanjappan
Ranch Hand

Joined: Aug 08, 2000
Posts: 40
Hi vadiraj,

The compiler error is , because

the class MyClassUsedInFinalizeTest is in package p.pack.
and the class FinalizeTest.java in package p.
Since the class FinalizeTest does not extends
the class MyClassUsedInFinalizeTest the protected
method MyClassUsedInFinalizeTest.meth() is not accessible
in class FinalizeTest package p.

Change the declaration of class FinalizeTest to
public class FinalizeTest extends MyClassUsedInFinalizeTest


</BLOCKQUOTE>

Hoping this may help....
Rosemol.
[This message has been edited by Rosemol Thanjappan (edited January 08, 2001).]
[This message has been edited by Rosemol Thanjappan (edited January 08, 2001).]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: can't access finalize() method !!!
 
Similar Threads
Possible BUG in VAJ 3.5.3 : Inner class
Method question
Byte -- what's going on
finalize()
println() : question from JQPlus