File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes object class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "object class" Watch "object class" New topic

object class

rahul mehra
Ranch Hand

Joined: Aug 20, 2007
Posts: 33
i'm writing a very simple program in which i do the following things :

a) create an object of apple type.
b) Create on object of Object type( since Object class is inherited by all the classes).

public class Apple {

public static void main(String[] args) {
Object o = new Object(); // 1
Apple m = new Apple(); // 2
m.clone(); // 3
o.clone(); // 4

question :

i get a complie time error in line 4 ( clone() is a protected access in java.lang.Object) but i can access the clone() method through the object of Apple class(line 3).

can you explain why???

Alexsandra Carvalho
Ranch Hand

Joined: Jul 13, 2007
Posts: 75
Hi deeksha,

In the Apple class you have access to clone method by inheritance (as you said). But you only can access the protected method of a class if the new class is in the same package or through another subclass in any package.

Neha Bhattad
Ranch Hand

Joined: Aug 20, 2007
Posts: 30
From Sun Java

>> The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.
rahul mehra
Ranch Hand

Joined: Aug 20, 2007
Posts: 33
hi neha,

well it dosen't throw any execption at runtime .... it gives me a compile time error....

clone() is a protected access in java.lang.Object
I agree. Here's the link:
subject: object class
It's not a secret anymore!