Java public keywordA Java public keyword is an access modifier. It can be assigned to variables, methods, constructors, and classes. It is the most non-restricted type of access modifier. Points to remember
Examples of public keywordExample 1Let's see an example to determine whether public variable and method is accessible or not outside the class. Here, we also try to create an instance of constructor outside the class. Output: Try to access a public variable outside the class Try to access a public method outside the class Try to create the instance of public constructor outside the class Example 2Let's see an example to determine whether public variable and method is accessible or not outside the package. Here, we also try to create an instance of constructor outside the package. Output: Try to access a public variable outside the package Try to access a public method outside the package Try to create the instance of public constructor outside the package Example 3Let's see an example to determine whether the public method is overridden to sub-class using public access modifier. Output: Try to access the overridden method Example 4Let's see an example to determine whether the public method is overridden to sub-class using private access modifier. Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot reduce the visibility of the inherited method from A Example 5Let's see an example to determine whether the public method is overridden to sub-class using default access modifier. Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot reduce the visibility of the inherited method from A Example 6Let's see an example to determine whether the public method is overridden to sub-class using protected access modifier. Output: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot reduce the visibility of the inherited method from A
Next TopicJava Keywords
|