Constructor and Destructor

Whenever you create an object, you need to construct that object, meaning you assign all the instance variables to their correct values. This makes sure the object will be in a valid state once it’s created.

The constructor is method has the same name of the class. It’s called as soon as you created an object. You can have multiple constructors.

Having two or more methods with the same name, but with different parameters, either in the number of the parameters, their sequence, or their data type, is called “method overloading”.

The same idea as having a method that will be called as soon as the object is created, there is another one whenever the object goes out of the scope.

In Java, there is no destructor since it’s garbage collected language, hence you can’t know when the object will be destroyed by the garbage collected. While in C++, this concept applies, and we do have a destructor.

Instance Members Vs Static Members

Maybe we need to have a member that will be the same for across all instantiated objects.

If that’s the case, we can create a static member that’s shared across all the class. So, there will be one and only one copy of this member.

Static members are shown with underline to differentiate between them and the instance members.

You access a static member through the class name, not the object instantiated, and also you can access it even if there is no objects have been instantiated yet.

Now, one important thing to know, you can’t trigger an instance methods or attributes inside a static method.

This should make sense for you, because, static methods aren’t tied to any object, so, these instance methods or attributes don’t belong to any object when we are trying to trigger them from inside a static method.

public class SavingsAccount {
   private int number;
   private static int interestRate;
   public static double getInterestRate(){
      // this.number = 5123;        // WRONG!
      return interestRate * 0.5;

Related Posts

Comments are closed.

© 2023 Software Engineering - Theme by WPEnjoy · Powered by WordPress