Access Modifiers The access modifiers in java specifies the accessibility or scope of a class by applying the access modifier on it. There are four types of Java access modifiers : Private Default Protected Public The access level of a private modifier is only within the class. It cannot be accessed from outside the class. The access level of a default modifier is only within the p ackage. If you do not specify any access level, it will be the default. The access level of a protected modifier is within the package and outside the package through child class. The access level of a public modifier is everywhere. It can be accessed from within the classes or outside the class.
Access Modifiers – A Comparison
Multiple Classes in Java The following program comprises of two classes: Computer and Laptop, both the classes have their constructors and a method. In the main method, we create objects of two classes and call their methods. Here, we can also create objects in a method of Laptop class. When we compile the program, two class files are created, which are Computer.class and Laptop.class.
M e t h ods A method is a block of code which only runs when it is called. You can pass data (parenthesis), into a method. They are used to perform certain actions, and they are also known as functions. Why use methods? It is used to reuse code which means to define the code once, and use it many times. A method must be declared within a class. It is defined with the name of the method, followed by parentheses ().
Creating a Method myMethod () is the name of the method. Static means that the method belongs to the Main class. It is not an object of the Main class. Void means that this method does not have a return value.
Diving into Class Concept Generally, classes can be used for two purposes: Container classes: a collection of static methods that are not bound to any particular object (e.g., the main() method). These static methods usually have something in common Definition classes: These classes define new objects, in a way that we will soon see. The Math class is an example of the first kind. It is a container for math utility methods: Math.sqrt () , Math.abs () , Math.max () , ... The class Clock is an example of the first kind. It defines a new type of objects, Clock objects. We will now focus on the second kind.