Keywords: super() – Calls the parent class constructor. this – Refers to the current instance. new – Creates objects dynamically.
Comparison: Abstract Class – Has both abstract and concrete methods; cannot be instantiated. Final Class – Cannot be extended; ensures fixed implementation. Interface – Defines method signatures; supports multiple inheritance.
1. Watch this tutorial alongside for a better understanding.
2. This Keyword in Java:
public class ThisInJava {
public static void main(String[] args) {
Student obj = new Student("Amit");
obj.display();
}
}
class Student{
String name;
Student(String name){
this.name = name;
}
void display() {
System.out.println(this.name);
}
}
3. Super Keyword in Java:
class Animal{
Animal(int a){
System.out.println("Animal constructor is called!: " + a);
}
boolean isItAnAnimal = true;
void sound() {
System.out.println("It is animal sound!");
}
}
class Dog extends Animal{
Dog(){
super(1);
System.out.println("Dog constructor is called!");
}
boolean isItAnAnimal = false;
void sound() {
super.sound();
System.out.println("It is dog sound!: " + super.isItAnAnimal);
}
}
public class SuperInJava {
public static void main(String[] args) {
Dog obj = new Dog();
obj.sound();
}
}
4. New Keyword in Java:
public class NewKeywordInJava {
public static void main(String[] args) {
String s1 = new String("ABC");
String s2 = "ABC";
CarService obj1 = new CarService("Red");
CarService obj2 = new CarService("Green");
CarService obj3 = new CarService("Black");
System.out.println("obj1: " + obj1.color);
System.out.println("obj2: " + obj2.color);
System.out.println("obj3: " + obj3.color);
}
}
class CarService{
String color;
CarService(String color){
this.color = color;
}
}
5. Abstract Class, Final Class and Interface in Java
public class FinalAndAbstractClassinJava {
public static void main(String[] args) {
class1 obj = new class1();
}
}
abstract class ABC{
abstract void display1();
void display2() {
}
}
class ABCD extends ABC{
void display1() {
}
}
//100% abstract class
interface interface1{
void display1();
abstract void display2();
}
interface interface2{
abstract void display3();
}
class ABCDE implements interface1, interface2{
public void display1() {
}
public void display2() {
}
public void display3() {
}
}
final class class1{
public void display4() {
System.out.println("display4");
}
}
class class2 extends class1{//error
}