PROGRAMMING

  MINTE9
REMEMBERS




Last update:   29-10-2021

Objects

p72 JVM allocates space for the reference variable.
 
/**
 * To use an object you must declare a reference variable.
 * JVM allocates space for the object.
 * 
 * The reference variable is forever of type Dog!
 * myDog = new Cat(); // will throw a type mismatch error
 */

package com.minte9.basics.objects;

public class Objects {
    public static void main(String[] args) {
    
        Dog myDog = new Dog();
        myDog.size = 40;
        myDog.bark();
    }
}

class Dog {
    int size;
    String name;
    
    void bark() {
        System.out.println("Ham Ham"); // Ham Ham
    }
}

class Cat {}

References

p77 A reference to an object can be overridden and the old reference is destroyed.
 
/**
 * There are 3 reference variables and 2 objects
 * 
 * After a overrites b, the b reference to object 2 is destroyed
 * (eligible for Garbage Collection)
 */

package com.minte9.basics.objects;

public class References {
    
    public static void main(String[] args) {
        
        Book a = new Book("A");
        Book b = new Book("B");
        System.out.printf("%s %s \n", a, b); // A B

        Book c = b; // refc / objB
        System.out.printf("%s %s %s \n", a, b, c); // A B B

        b = a; // refb / objA
        System.out.printf("%s %s %s \n", a, b, c); // A A B
    }
}

class Book {
    String name;   

    public Book(String name) { // contructor
        this.name = name;
    }
    public String toString() {
        return name;
    }
}

Questions     github Basics
Arrays
        A B C D E F
🔔
1/5