Referencing

  • You can create reference variable data-type as same as object’s, superclass or interface.
class Animals {
     public void bark(){
         System.out.println("animal is barking");
     }
}
 
interface DogIF {
    public void dogging();
}
 
class Dog extends Animals implements DogIF {
    public void bark(){
        System.out.println("dog is barking");
    }
 
    public void dogging() {
        System.out.println("dogging");
 
    }
}
 
 
public class Animals {
    public static void main(String[] args) {
        Dog dog = new Dog();
        // accessible: dog.bark(), dog.dogging()
 
        Animal animal = new Dog();
        // accessible: dog.bark() but Dog class's version
 
        DogIF dog2 = new Dog();
        // accessible: dog.dogging() but Dog class's version
    }
}

Pass by Value and Reference

  • Java is always pass by value
  • For class objects, the variables actually are just references itself
  • For primitives the variable hold the value
  • All wrapper classes like Integer in java are immutable
Integer x = 3; // x holds a reference
Integer y = x; //  y and x point to the same memory address
System.out.println(x + " " + y); // 3 3
System.out.println(System.identityHashCode(x) + " " + System.identityHashCode(y)); // 317983781 317983781
 
 
// since Integer is immutable
// following is same as y = new Integer(7);
y = 7; 
System.out.println(x + " " + y); // 3 7
System.out.println(System.identityHashCode(x) + " " + System.identityHashCode(y)); // 317983781 1599771323