The three principals of OOP are as follows:
- Encapsulation is the simplest of all. It means that data of the object and operations on the data are packaged together in one class.
- 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.
- 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:
- Primitive
- Objects
There are 8 primitive types and each one of them has primitive wrapper:
Type | Size | Wrapper Class | Notes |
boolean | 1 bit | Boolean | true or false |
byte | 8 bit | Byte | -128 to 127 |
char | 16 bit Unicode | Character | 0 to 65536 |
short | 16 bit | Short | -32,768 to 32,767 |
int | 32 bit | Integer | -2^31 to 2^32 -1 |
long | 64 bit | Long | -2^64 to 2^64 -1 |
float | 32 bit | Float | |
double | 64 bit | Double |
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>