DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-63 Understanding difference b/w Static and Non-Static Methods, and Inheritance in Java

Static vs. Non-Static Methods

Non-static methods need an object to call them because they belong to the instance of the class, not the class itself.

Static methods belong to the class itself, not to any object. Hence, we cannot use the this keyword inside static methods because this refers to the current object, but static methods do not have an object context.

key Points

  • this is an internal reference to the current object and cannot be used in static methods.
  • Object = memory reference to class data.
  • We can use the class name to call static methods from different classes.

Inheritance in Java

Inheritance allows us to create a new class based on an existing class, reusing code and creating a relationship between parent and child classes.

Key Points:

  • extends keyword is used for inheritance.
  • Parent class = Superclass or base class
  • Child class = Subclass or derived class
  • Object of one class acting as another:
    • Possible from parent to child but not from child to parent directly.
  • super keyword is used to refer to the superclass object or constructor.

Example

package salem;
public class Parent {
    public Parent() {
        System.out.println("parent-const"); // default constructor
    }

    public Parent(int i) {
        System.out.println("parent-one arg - const"); // one argument constructor
    }

    public void useLaptop() { // non static method
        System.out.println("using laptop");
    }
}

package salem;
public class Child extends Parent {
    public Child() {
        super(10); // calls Parent(int i) constructor
        System.out.println("child-const");
    }

    public static void main(String[] args) {
        Child ch = new Child(); // An object of Child class acting as an object of Parent class - inheritance

        // Parent pp = new Parent(); // without extends keyword we have to create object
        // pp.useLaptop();

        ch.play(); // calling child method
        ch.useLaptop(); // calling parent method using child object
    }

    public void play() {
        System.out.println("playing");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

parent-one arg - const
child-const
playing
using laptop
Enter fullscreen mode Exit fullscreen mode

Top comments (0)