The following are my notes on OOP course (Object-oriented programming) based on Kunal Kashwaha’s lectures on YouTube (link in the reference section)
Access control / Access modifiers
4 Types of access modifiers:
public
: accessible everywhere
private
: only accessible in the same class (file)
- default: when a specific access modifier is not specified.
protected
: useful when inheritance is involved
Purpose of having access control:
For security, restricting access to the data members
protected
with inheritance
The access level of a protected modifier is within the package and outside the package through child class.
Parent class
package packageOne; public class Base { protected void display(){ System.out.println("in Base"); } }
Child class
package packageTwo; public class Derived extends packageOne.Base{ public void show(){ new Base().display(); // this is not working new Derived().display(); // is working display(); // is working } }
new Base().display()
is not working because the caller's (the this instance) class is not defined in the same package so the protected method “display” cannot be accessedAccess modifiers with method overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
class A{ protected void msg() { System.out.println("Hello java"); } } public class Simple extends A{ void msg(){System.out.println("Hello java");}//Compile Time Error public static void main(String args[]){ Simple obj=new Simple(); obj.msg(); } }
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
Object Class in Java
The Object class is the parent class of all the classes in java by default.
It provides multiple methods which are as follows (and these functions can be overridden)
toString()
method
It is always recommended to override the
toString()
method to get our own String representation of Object.// Default behavior of toString() is to print class name, then // @, then unsigned hexadecimal representation of the hash code // of the object public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
hashCode()
method
It returns distinct integers for distinct objects. It converts the internal address of the object to an integer by using an algorithm. The main advantage of saving objects based on hash code is that searching becomes easy.
equals(Object obj)
method
finalize()
method
This method is called just before an object is garbage collected. Called only once on a object even though the object might be collected multiple times by garbage collector
getClass()
method
It can also be used to get metadata of this class.
clone()
method
wait()
,notify()
,notifyAll()
methods: related to concurrency