2

I know by inheritance all classes inherit methods from Object class.Similarly if we extends one class with other it also inherit method. Then why we can call inherited protected method from other class and not able to call inheritate method from Object class

package com.core.test;

public class CloneableTest {
    public static void main(String[] args) {
        Testclass test= new Testclass();        

        test.someClassSpecificMethod();
        test.clone();  //ERROR AT tHIS LINE why                  
    }
}

class SomeClass implements Cloneable {

    protected void someClassSpecificMethod(){

    }
}

class Testclass extends SomeClass {

} 

In above file As I can able to access someClassSpecificMethod using instance of Testclass then why I cannot able to access clone method?

Javakar
  • 21
  • 2

2 Answers2

2

Because clone is not defined in a class residing in the same package as CloneableTest, whereas someClassSpecificMethod is. A class can only access the protected method it inherited from its parent, and even if it inherits from the same parent as the other class, it still cannot access the method from the other class. This makes perfect sense with respect to the intention behind protected: it is public API a base class provides to its children, but not to the class's clients.

Since protected is strictly wider than package-private, you can always access a protected method that you could access if it was package-private, and such is the case with someClassSpecificMethod.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
1

You can access protected methods of classes from your own package only when the methods are declared in the class that you are accessing. Both the class and its method must be in the same package, otherwise it is not going to work. Since Object's clone method is declared as part of Object in java.lang package, you cannot access clone unless you also declare an override in your package:

class SomeClass implements Cloneable {
    @Override
    protected Object clone() {
        ... // Do something here
    }
}

Now you can call clone from the same package, as long as you declare a variable of type SomeClass:

SomeClass sc1 = new SomeClass();
SomeClass sc2 = (SomeClass)sc1.clone();
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523