Friday, November 18, 2022

Access Modifiers In Java With Examples And Best Practices

In this tutorial, I will be sharing what are the different types of access modifiers in java, scope and definition of each access modifier with an example program, and best practices. As the title gives the hint, access modifiers allow us to restrict the scope of the variable, method, class or constructor.


The four types of access modifiers in java are:

1. public
2. protected
3. default
4. private


Access Modifier in Java


Private:

A private access modifier offers the highest level of access restriction. The access level of a private access modifier is only within the class. The data members and methods declared as private cannot be accessed from outside the class.

Private Access Modifier Example:

The below program results in a compile-time error as we are attempting to access the private data member and method of class A in class B.

class A
{
    private int totalValue = 50;
    private int Multiply(int a,int b)
    {
        return a*b;
    }
}

public class B
{
    public static void main(String args[])
    {
        A object = new A();
        System.out.println(object.totalValue); //accessing private data member of class A
        System.out.println(object.Multiply(10,15)); // accessing private method of class A
    }
}


Output:
Compilation error
/B.java:17: error: totalValue has private access in A
            System.out.println(object.totalValue); 
                                     ^
/B.java:18: error: Multiply(int,int) has private access in A
            System.out.println(object.Multiply(10,15)); 
                                     ^

2 errors


Default:

When no access specifier is given, it will be considered the default access specifier. It is also known as "package-private" or "no modifier". The default access modifier allows access only within the package. It does not allow access from outside the package.

Default Access Modifier Example:

In the below example program, we have two classes Controller and Multiplication. In class Controller, I am attempting to access the Multiply() method of Multiplication class which has default access. Since class Controller is present in an alternate package i.e B and the scope of default modifier is restricted to a current package level i.e A, this program would result in compilation error.

Multiplication.java

package A;
public class Multiplication {
/* As we haven't specified any access modifier here,
* it will be considered as default.
*/
int Multiply(int an, int b){
    return a*b;
  }
}


Controller.java

package B;
import A.*;
public class Controller {
public static void main(String args[])
  {
    Multiplication object = new Multiplication ();
    object.Multiply(10, 21);
  }
}


Output:
Exception in thread “main” java.lang.Error : Unresolved compilation problem:The method Multiply(int,int) from the type Multiplication is not visible at B.Controller.main(Controller.java:6)

Protected:

The protected access modifier provides access within the package and outside the package through inheritance only i.e by creating child class (subclass or derived class). It cannot be accessed from outside the package if there is no inheritance.

Protected Access Modifier Example:

In this example, the class Controller which is available in another package B can access the Multiply() method, which is declared as protected. This is possible since the class Controller extends class Multiplication. Subclasses of the Multiplication class present in any package can access the protected methods or data members.

Multiplication.java

package A;
public class Multiplication {
protected int multiply(int a, int b){
    return a*b;
  }
}


Controller.java

package B;
import A.*;
class Controller extends Multiplication {
/*
* Controller is a sub-class of Multiplication
*/
  public static void main(String args[]){
    Controller object = new Controller ();
    System.out.println(object.multiply(11, 22));
  }
}


Output:
33

Public:

The public access modifier offers the lowest level of access restriction. Class or variable or method declared as public can be accessed everywhere. Once a variable or method is declared public, it can be accessed from anywhere in the code, i.e within the class, outside the class, within the package and outside the package.

Public Access Modifier Example:

The below example is equivalent to the one we have seen for private access modifier however here the method Multiply () has public modifier and class Controller can access it.

Multiplication.java

package A;
public class Multiplication {
/*As Multiply is made public it can be accessed
*anywhere globally
*/
public int Multiply (int an, int b){
    return a*b;
  }
}


Controller.java

package B;
import A.*;
class Controller {
public static void main(String args[]){
    Multiplication object = new Multiplication ();
    System.out.println(object.Multiply(100, 2));
  }
}


Output:
200


Points to Remember:


1. Classes in java are allowed to use only the "public" or "default" access modifier.

2. Class members i.e variables and methods are allowed to use any of the four access modifiers.

3. We are allowed to have only one public class in a source file. public class name must be the same as the source file.

4. The default access modifier is also known as "package-private" or "no-modifier".

5. Examples of non-access modifiers are static, transient, abstract, synchronized.


Best Practices To Use Access Modifiers:


1. Prefer the most restrictive access level that makes sense for a particular member.

2. Use public fields for constants only.


Access Modifiers in Java with Method Overriding

The access modifier of a overriding method(declared in a subclass) must not be more restrictive than the access modifier of an overridden method(declared in superclass).

In the below example class Child hello() method has a default access modifier. It is overriding the Parent class hello() method which has a protected access modifier. As we know, the default access modifier is more restrictive than a protected access modifier. Hence, the below code will throw the compile-time error.


class Parent
{
    /*overridden method has 
      protected access modifier*/ 
    protected void hello()
    {
        System.out.println("Alive is Awesome");
    }
}

public class Child extends Parent
{
    /*overriding method has
      default access modifier */ 
    void hello()
    {
        System.out.println("Be in present");
    }
    
    public static void main(String args[]) {
      Child obj = new Child();
      obj.hello();
    }
}


Output:
/Child.java:11: error: hello() in Child cannot override hello() in Parent
    void hello()
         ^
  attempting to assign weaker access privileges; was protected
1 error


That's all for today. Please let me know in the comments in case you have any questions related to access modifiers in java.

.link.

Tuesday, November 8, 2022

Java Buzzwords or Features of Java

 The Java programming language is a high-level language that can be characterized by all of the following buzzwords:

  1. Simple
  2. Object-oriented
  3. Distributed
  4. Interpreted
  5. Robust
  6. Secure
  7. Architecture neutral
  8. Portable
  9. High performance
  10. Multithreaded
  11. Dynamic

1. Simple

  • Java was designed to be easy for a professional programmer to learn and use effectively.
  • It’s simple and easy to learn if you already know the basic concepts of Object Oriented Programming.
  • Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.
  • Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.

2. Object Oriented

  • Java is true object-oriented language.
  • Almost “Everything is an Object” paradigm. All program code and data reside within objects and classes.
  • The object model in Java is simple and easy to extend.
  • Java comes with an extensive set of classes, arranged in packages that can be used in our programs through inheritance.
  • Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules.
Basic concepts of OOPs are:
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

3. Distributed

  • Java is designed fa or distributed environment of the Internet. Its used for creating applications on networks.
  • Java applications can access remote objects on the Internet as easily as they can do in the local system.
  • Java enables multiple programmers at multiple remote locations to collaborate and work together on a single project.
  • Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols.

4. Compiled and Interpreted

  • Usually, a computer language is either compiled or Interpreted. Java combines both this approach and makes it a two-stage system.
  • Compiled: Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java Bytecode.
  • Interpreted: Bytecode is then interpreted, which generates machine code that can be directly executed by the machine that provides a Java Virtual machine.

5. Robust

  • It provides many features that make the program execute reliably in a variety of environments.
  • Java is a strictly typed language. It checks code both at compile time and runtime.
  • Java takes care of all memory management problems with garbage collection.
  • Java, with the help of an exception handling, captures all types of serious errors and eliminates any risk of crashing the system.

6. Secure

  • Java provides a “firewall” between a networked application and your computer.
  • When a Java Compatible Web browser is used, downloading can be done safely without fear of viral infection or malicious intent.
  • Java achieves this protection by confining a Java program to the Java execution environment and not allowing it to access other parts of the computer.

7. Architecture Neutral

  • Java language and Java Virtual Machine helped in achieving the goal of “write once; run anywhere, any time, forever.”
  • Changes and upgrades in operating systems, processors and system resources will not force any changes in Java Programs.

8. Portable

  • Java Provides a way to download programs dynamically to all the various types of platforms connected to the Internet.
  • It helps in generating Portable executable code.

9. High Performance

  • Java performance is high because of the use of bytecode.
  • The bytecode was used so that it was easily translated into native machine code.

10. Multithreaded

  • Multithreaded Programs handled multiple tasks simultaneously, which was helpful in creating interactive, networked programs.
  • Java run-time system comes with tools that support multiprocess synchronization used to construct smoothly interactive systems.

11. Dynamic

  • Java is capable of linking in new class libraries, methods, and objects.
  • Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at runtime. This makes it possible to dynamically link code in a safe and expedient manner.

CORBA Java Tutorial using Netbeans and Java 8.

CORBA-Example A simple CORBA implementation using Java Echo.idl module EchoApp{ interface Echo{ string echoString(); }; }; ...