Skip to content

Instantly share code, notes, and snippets.

@Blasanka
Created March 31, 2017 20:02
Show Gist options
  • Save Blasanka/d8797b76523514d38cda1978ddf659d0 to your computer and use it in GitHub Desktop.
Save Blasanka/d8797b76523514d38cda1978ddf659d0 to your computer and use it in GitHub Desktop.
This code snippet about final keyword in java. As a intro - We can use final keyword to variable then that variable become constant and if we use final keyword to a method that method cannot override and if we use for class that class stop inheriting.
class Father {
//delete final to get rid from error
public final void doingNow(){
System.out.println("reading book");
}
}
//final class cannot have child classes
//delete final to get rid from error
final class Son extends Father{
//final method cannot override
//overridden method
public void doingNow(){
System.out.println("Watchin TV");
}
public static void main(String[] args) {
//there is no point of having constant variable without initializing
//final int WIDTH;
//use upper case for constant(final) variables.
//final int WIDTH = 30;
//System.out.println(width);
//example for constant variable
//Math.PI
//without final we can change value of width
//width = 50;
//System.out.println(width);
//have to create object of this class otherwise we cannot access to a doingNow()
//because cannot call non-statitc method in static method.
Son firstSon = new Son();
firstSon.doingNow();
}
}
//if we add final to son class son class cannot be a parent for grandSon class.
class grandSon extends Son{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment