Java: Access Modifiers and Constructors

Java: Access Modifiers and Constructors

- VINAYAK PANCHAL

INTRODUCTION

Java is an object-oriented programming language, hence everything in Java is associated with classes and objects. You must be quite familiar with the public keyword that appears when we write our main class and data types. This public keyword is an access modifier, which means that it is used to set the access level for classes, methods, and constructors. We will also understand what are constructors and why we even need them. So now,

LetsStartFromTheBeginningZootayGIF.gif

Modifiers

Modifiers are divided into two groups:

Access Modifiers -------> controls the Access level

Non-Access Modifiers -------> do not control access level but provide other functionality

Access Modifiers

If you want to define for classes then use public or default modifiers :

Access Modifiers (1).png

A public class is accessible by all the classes in the same package as well as from classes in the other packages. A default modifier can be considered as a modifier that does not modify the class. When a class is neither public, private, or protected it is the default.

For attributes, methods, and constructors, refer to the following table :

Access Modifiers (2).png

I know, reading the official Oracle Docs. for Java could be boring. But I found something, which will help us understand the above description actually quite easily in the official documentation. (Here default == no modifier)

Access Modifiers (3).png

Non-Access Modifiers

For classes, refer to the below table :

Access Modifiers (4).png

For attributes and methods, refer to the below table :

Access Modifiers (5).png

Final, static and abstract

If you don't want the ability to override existing attribute values, declare attributes as final. The final keyword declares the attributes as final and makes them immutable. In Interfaces, the datatypes are by default considered to be final, so this keyword becomes unimportant inside an Interface, but while making a normal class and declaring datatypes final makes them unavailable for overriding purposes. See, the following example, for a better understanding :

public class Main {
  final int x = 10;
  final double Pi = 3.14;

  public static void main(String[] args) {
    Main fif = new Main();
    fif.x = 50; // throws an error, because final declared datatypes cannot be overrided
    fif.Pi = 3.1426 ; // throws an error, because final declared datatypes cannot be overrided
    System.out.println(fif.x);
  }
}

Static vs. Public

Before moving on to static, let us first understand the difference between static and public keywords given to methods inside a class. A public method is a method that can be called only by creating an object out of the class in which that public method exists. While in the case of a static method, A static method means that it can be accessed without creating an object of the class. See the following example, for a better understanding :

public class Main {
  static void staticMethod() {
    System.out.println("Static methods are called without creating an object of the class ! ");
  }

  public void publicMethod() {
    System.out.println("Public methods must be called by creating object of the class ! ");
  }

  public static void main(String[ ] args) {
    staticMethod(); // Calls the static method successfully 🥳
    publicMethod(); // Throws an error, we need to make an object 

    Main Obj = new Main(); // Create an object of Main
     Obj.publicMethod(); // Calls the public method successfully 🥳
  }
}

Moving onto the abstract class, let us first understand what abstract means. When you will Google it, it will show you :

Abstract = existing only as an idea, not as a physical thing

If a class contains a method that is declared without an implementation, then it is known as an abstract class. You can also declare it by mentioning the abstract keyword before the class keyword. When the abstract class is subclassed i.e. inherited then the subclass usually provides the implementation. If it fails to do that then it must be also declared as an abstract class! Look at the below example :

// Code from filename: Main.java
// abstract class
abstract class Main {
  public String fname = "John";
  public int age = 24;
  public abstract void study(); // abstract method
}

// Subclass (inherit from Main)
class Student extends Main {
  public int graduationYear = 2018;
  public void study() { // the body of the abstract method is provided here
    System.out.println("Studying all day long");
  }
}
// End code from filename: Main.java

// Code from filename: Second.java
class Second {
  public static void main(String[] args) {
    // create an object of the Student class (which inherits attributes and methods from Main)
    Student myObj = new Student();

    System.out.println("Name: " + myObj.fname);
    System.out.println("Age: " + myObj.age);
    System.out.println("Graduation Year: " + myObj.graduationYear);
    myObj.study(); // call abstract method
  }
}

Constructors in Java

A constructor is a member function used to initialize an object while creating it. The constructor is called when an object of a class is created. The values are already set in the constructor and get invoked automatically if we didn't have setters declared in the code base.

// Create a Main class
public class Main {
  int x;  // Create a class attribute

  // Create a class constructor for the Main class
  public Main() {
    x = 5;  // Set the initial value for the class attribute x
  }

  public static void main(String[] args) {
    Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
    System.out.println(myObj.x); // Print the value of x
  }
} 
// 5 is the output

IMPORTANT POINTS TO BE REMEMBERED WHILE CREATING CONSTRUCTORS

  • The Constructor name must match the class name

  • It cannot have a return type

  • The constructor is called when the object is created.

Constructor Parameters

Constructors can also take parameters, which are used to initialize attributes. Constructors can be overloaded like other methods in Java. In fact, You can have as many parameters as you want. Have a look at the below example for a better understanding:

public class Main {
  int modelYear;
  String modelName;

  public Main(int year, String name) {
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args) {
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName);
  }
}

// Outputs 1969 Mustang

That's a Wrap!

Thank you for reading till the end :D

I write articles on Java and will soon start writing on HTML, CSS, Javascript and other backend technologies ( actually on FULL STACK DEVELOPMENT =D)

Follow me on Twitter: vinayakstwt 🕊️

Follow me on HashNode: VINAYAK PANCHAL 📄