Java – The basics

The three principals of OOP are as follows:

  1. Encapsulation is the simplest of all. It means that data of the object and operations on the data are packaged together in one class.
  2. Inheritance lets us base a new class on existing one, where we choose common functionality. Java includes 2 types of inheritance.
    • Implementation : With this the subclass includes the state of the base class.
    • Interface : Every field declared in the interface is immediately made static, final and public. That makes all fields implicitly constants. All methods are implicitly public.
  3. Polymorphism : A subclass can stand in place of different object and replace the underlying implementation seamlessly.
class BaseClass{
   public void helloWorld{
       System.out.println("Hello World");
   }
}
class subClass extents BaseClass{
    @overide
    public void helloWorld(){
        System.out.println("Hello World from subclass");
    }
}

BaseClass subClass = new SubClass();
subClass.helloWorld();
// The above code will print "Hello World from subclass".

Java has two basic types of groups:

  1. Primitive
  2. Objects

There are 8 primitive types and each one of them has primitive wrapper:

TypeSizeWrapper ClassNotes
boolean1 bitBooleantrue or false
byte8 bitByte-128 to 127
char16 bit UnicodeCharacter0 to 65536
short16 bitShort-32,768 to 32,767
int32 bitInteger-2^31 to 2^32 -1
long64 bitLong-2^64 to 2^64 -1
float32 bitFloat
double64 bitDouble
Java primitive types and wrappers

Everything else is an object, including arrays. Objects can be customised with generic types, but those types are removed in runtime due to erasures that lead to unexpected behaviours, such as ability to add string to a list of integers.

Generics and Erasure

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.

// Java 5 Syntax
List<String> stringList = new ArrayList<String>();

// Java 8 Diamond Operator
List<String> stringList = new ArrayList<>();

//the var keyword
var stringList = new ArrayList<String>();

A simple generic can be declared within the class declaration code as :

public class MyClass<T>{
    T value;
    public T getValue(){
        return value;
    }
    public void setValue(T value){
        this.value = value;
    }
}

// usage
MyClass<Integer> myObj = new MyClass<>();
myObj.setValue(3);

// Generics can represent using the wildcard such as MyClass<? extends Number> or say we have an API that accepts an Integer but might work with one of its base classes (Number or Object); we can use the syntax MyClass<? super Number>

Leave a Reply

Your email address will not be published. Required fields are marked *