Skip to main content

SUMMARY

1)

Protected members can be accessed directly or with super or this keyword in subclass of different package.


2)

Protected members cannot be accessed outside the package:

a)

With object of superclass.

b)

With one subclass object in other subclass.


3)

Private variables cannot be accessed from outside the class.


4)

You can use constructors or setter methods to modify the value of private variables.


5)

You can use getter methods to access the value of private variables from outside the class.


Access Rights for Different Elements

Access Typeprivatedefault (no modifier)protectedpublic
Same classYESYESYESYES
SubclassNOYESYESYES
Non subclassNOYESYESYES
Subclass using super keywordNONOYESYES
Subclass using current subclass objectNONOYESYES
Subclass using superclass objectNONONOYES
Subclass using other subclass objectNONONOYES
Non subclass another package

6)

When you modify the method arguments in subclass then it is method overloading not overriding.


7)

When your superclass method return type is primitive then you have to use exactly same return type while overriding this method in subclass.


8)

When your superclass method return type is class type then you can use exactly same return type or covariant type (subclass of superclass method return type) while overriding this method in subclass.


9)

Final method of superclass cannot be overridden in subclass.


10)

Non-final method of superclass can be overridden as final in subclass.


11)

Native method of superclass can be overridden as non-native in subclass.


12)

Non-native method of superclass can be overridden as native in subclass.


13)

strictfp method of superclass can be overridden as non-strictfp in subclass.


14)

Non-strictfp method of superclass can be overridden as strictfp in subclass.


15)

Synchronized method of superclass can be overridden as non-synchronized in subclass.


16)

Non-synchronized method of superclass can be overridden as synchronized in subclass.


17)

Private methods of superclass will not be visible to subclasses. So whatever method you are writing in subclass that will be treated as new method not overridden method.


18)

Access modifiers of subclass method must be same or higher than superclass method.


19)

In the case of method overriding:

a)

When you invoke the method with superclass object then method will be called from superclass only.

b)

When you invoke the method with subclass object then method will be called from subclass only.