Constructors, Static/Final Keywords, Interfaces, and Abstract Classes in Java


Let’s continue our Java fundamentals series from last week. In this post, I would like to talk about the basics of the constructors, static/final keywords, interfaces, and abstract classes in Java.

white notebook

A constructor in Java is like a method but is used to instantiate objects. Every time we use the new keyword to create an object, at least one constructor is triggered. Keys fact about constructors: a constructor must have the same name as the class, a constructor doesn’t return anything, a constructor can only be called once, and a constructor can have no argument or be parameterized. In Java, a constructor is mainly used to initialize the state of an object.

In Java, the static keyword is used for a constant variable or a method that stayed the same for every instance of the class. A static variable is essentially a global variable. That said, all instances of the classes share the same static variables. If a method is static, it can be accessed without creating an instance of the class. The final keyword is kind of like the static keyword in the sense that it is used to declare constant variables. However, if a method or a class is declared final, then they cannot be overridden or inherited.

An interface is a mechanism in Java that is used to achieve abstraction. It specifies what a class should do but not how the class does them. An interface is about capabilities like an animal can be an interface and any class implementing an Animal must implement sleep(). Any class that implements the interface must implement all the methods specifics in the interface. An abstract keyword is used when a class implemented an interface but not all the methods inside the interface. The implements keyword is used when a class implements an interface, and a class can implement more than one interface.

Now, let’s talk about the abstract class. An abstract class in Java cannot be used to instantiate objects. The static and final keywords can be used in an abstract class but any abstract method in the abstract class cannot be declared as final. A constructor can also be used in the abstract class. It’s allowed to define an abstract class without any abstract methods, this means even though we cannot use the class to instantiate objects, we can still inherit from it. Lastly, static methods can be defined in the abstract class, and we can use them without instantiating an object like an interface.

I hope you enjoyed reading this post and learned something new about Java.

Print Friendly, PDF & Email

Leave a Reply

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