Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object class

 
rahul mehra
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Alexsandra
 
Neha Bhattad
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic