Objects
/**
* To use an object you must declare a reference variable.
* JVM allocates space for the object.
*
* The reference variable is forever of that type.
* You cannot assign an object to another type.
* myDog = new Cat(); // ❌ 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;
void bark() {
System.out.println("Ham Ham"); // Ham Ham
}
}
References
/**
* A reference to an object can be overridden
*
* 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 /", a, b); // AB
Book c = b; // refc, objB
System.out.printf("%s%s%s /", a, b, c); // ABB
b = a; // refb, objA, objB destroyed
System.out.printf("%s%s%s /", a, b, c); // AAB
}
}
class Book {
String name;
public Book(String name) { // contructor
this.name = name;
}
public String toString() {
return name;
}
}
Autoboxing
/**
* Java has a two-part type system, primitives (int, double, boolean, etc) and
* reference types (String, List, etc).
*
* Every primitive type has a corresponding reference type, called boxed primitive.
* (Integer, Double, Boolean, etc).
*
* Autoboxing reduces the verbosity, bot not the danger, of using boxed primitives.
* Unboxing is the automatic conversion of objects into their coresponding primitives.
*/
package com.minte9.basics.objects;
import java.util.List;
import java.util.ArrayList;
public class Autoboxing {
public static void main(String[] args) {
List<Integer> li = new ArrayList<>();
for (int i=10; i<20; i++) {
li.add(i); // autoboxing (i is primitive)
}
System.out.println(li.get(0).getClass().getName()); // java.lang.Integer
int b = li.get(0); // unboxing (element is Integer)
System.out.println(b); // 10
}
}
Questions and answers:
Clink on Option to Answer
1. Things that an object knows are named
- a) methods
- b) instance variables
2. Variable declaration tells JVM to
- a) allocate a space for the reference
- b) allocate space for object
3. In Java a reference type can be changed
- a) true
- b) false
4. JVM allocates a space for object
- a) after using new myObject()
- b) after using return
5. Overwriting an object reference
- a) copy the reference
- b) destroy the old reference
6. Autoboxing is the automatic conversion between
- a) wrapper classes and primitives
- b) primitives and corresponding wrapper objects