Can class be protected in java

Protected class in java

Yes, we can declare a class as protected but these classes can be only inner or nested classes. We can’t a top-level class as protected because declaring top class as protected will mean that it is accessible to the current package as well as sub packages. Now there’s no concept of sub packages in Java.
Example 1 with non inner class:

protected class Main { public static void main(String[] args) { System.out.println("Inside protected class"); } }
Main.java:8: error: modifier protected not allowed here protected class Main ^ 1 error

Main.java:8: error: modifier protected not allowed here protected class Main ^ 1 error

Example 2 with non inner class:

protected class Show{ void display(){ System.out.println("Inside display method."); } } public class Main { public static void main(String[] args) { Show show = new Show(); show.display(); } }
Main.java:1: error: modifier protected not allowed here protected class Show{ ^ 1 error

Main.java:1: error: modifier protected not allowed here protected class Show< ^ 1 error

Example with inner class:

class Display { //Private nested or inner class protected class InnerDisplay { public void display() { System.out.println("Protected inner class method called"); } } void display() { System.out.println("Outer class (Display) method called"); // Access the protected inner class InnerDisplay innerDisplay = new InnerDisplay(); innerDisplay.display(); } } public class Main { public static void main(String args[]) { // Create object of the outer class (Display) Display object = new Display(); // method invocation object.display(); } }
Outer class (Display) method called Protected inner class method called

Outer class (Display) method called Protected inner class method called

Читайте также:  What is r java class in android

Java interview questions on access modifiers

Источник

Controlling Access to Members of a Class

Access level modifiers determine whether other classes can use a particular field or invoke a particular method. There are two levels of access control:

  • At the top level— public , or package-private (no explicit modifier).
  • At the member level— public , private , protected , or package-private (no explicit modifier).

A class may be declared with the modifier public , in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes — you will learn about them in a later lesson.)

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected . The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

The following table shows the access to members permitted by each modifier.

Access Levels

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class declared outside this package have access to the member. The fourth column indicates whether all classes have access to the member.

Access levels affect you in two ways. First, when you use classes that come from another source, such as the classes in the Java platform, access levels determine which members of those classes your own classes can use. Second, when you write a class, you need to decide what access level every member variable and every method in your class should have.

Let’s look at a collection of classes and see how access levels affect visibility. The following figure shows the four classes in this example and how they are related.

Classes and Packages of the Example Used to Illustrate Access Levels

The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.

Visibility

Modifier Alpha Beta Alphasub Gamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.

  • Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.
  • Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Источник

Java ‘protected’ Access Modifier

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In the Java programming language, fields, constructors, methods, and classes can be marked with access modifiers. In this tutorial, we’ll look at protected access.

2. The protected Keyword

By using the protected keyword, we make decisions about which methods and fields should be considered internals of a package or class hierarchy, and which are exposed to outside code.

3. Declaring protected Fields, Methods, and Constructors

First, let’s create a class named FirstClass containing a protected field, method, and constructor:

public class FirstClass < protected String name; protected FirstClass(String name) < this.name = name; >protected String getName() < return name; >>

With this example, by using the protected keyword, we’ve granted access to these fields to classes in the same package as FirstClass and to sub-classes of FirstClass.

4. Accessing protected Fields, Methods, and Constructors

4.1. From the Same Package

Now, let’s see how we can access protected fields by creating a new GenericClass declared in the same package as FirstClass:

public class GenericClass < public static void main(String[] args) < FirstClass first = new FirstClass("random name"); System.out.println("FirstClass name is " + first.getName()); first.name = "new name"; >>

As this calling class is in the same package as FirstClass, it’s allowed to see and interact with all the protected fields, methods, and constructors.

4.2. From a Different Package

Let’s now try to interact with these fields from a class declared in a different package from FirstClass:

public class SecondGenericClass < public static void main(String[] args) < FirstClass first = new FirstClass("random name"); System.out.println("FirstClass name is "+ first.getName()); first.name = "new name"; >>

As we can see, we get compilation errors:

The constructor FirstClass(String) is not visible The method getName() from the type FirstClass is not visible The field FirstClass.name is not visible

That’s exactly what we were expecting by using the protected keyword. This is because SecondGenericClass is not in the same package as FirstClass and does not subclass it.

4.3. From a Sub-Class

Let’s now see what happens when we declare a class extending FirstClass but declared in a different package:

public class SecondClass extends FirstClass < public SecondClass(String name) < super(name); System.out.println("SecondClass name is " + this.getName()); this.name = "new name"; >>

As expected, we can access all the protected fields, methods, and constructors. This is because SecondClass is a sub-class of FirstClass.

5. protected Inner Class

In the previous examples, we saw protected fields, methods, and constructors in action. There is one more particular case — a protected inner class.

Let’s create this empty inner class inside our FirstClass:

package com.baeldung.core.modifiers; public class FirstClass < // . protected static class InnerClass < >>

As we can see, this is a static inner class, and so can be constructed from outside of an instance of FirstClass. However, as it is protected, we can only instantiate it from code in the same package as FirstClass.

5.1. From the Same Package

To test this, let’s edit our GenericClass:

public class GenericClass < public static void main(String[] args) < // . FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); >>

As we can see, we can instantiate the InnerClass without any problem because GenericClass is in the same package as FirstClass.

5.2. From a Different Package

Let’s try to instantiate an InnerClass from our SecondGenericClass which, as we remember, is outside FirstClass’ package:

public class SecondGenericClass < public static void main(String[] args) < // . FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); >>

As expected, we get a compilation error:

The type FirstClass.InnerClass is not visible

5.3. From a Sub-Class

Let’s try to do the same from our SecondClass:

public class SecondClass extends FirstClass < public SecondClass(String name) < // . FirstClass.InnerClass innerClass = new FirstClass.InnerClass(); >>

We were expecting to instantiate our InnerClass with ease. However, we are getting a compilation error here too:

The constructor FirstClass.InnerClass() is not visible

Let’s take a look at our InnerClass declaration:

protected static class InnerClass

The main reason we are getting this error is that the default constructor of a protected class is implicitly protected. In addition, SecondClass is a sub-class of FirstClass but is not a sub-class of InnerClass. Finally, we also declared SecondClass outside FirstClass’ package.

For all these reasons, SecondClass can’t access the protected InnerClass constructor.

If we wanted to solve this issue and allow our SecondClass to instantiate an InnerClass object, we could explicitly declare a public constructor:

protected static class InnerClass < public InnerClass() < >>

By doing this, we no longer get a compilation error, and we can now instantiate an InnerClass from SecondClass.

6. Conclusion

In this quick tutorial, we discussed the protected access modifier in Java. With it, we can ensure exposing only the required data and methods to sub-classes and classes in the same package.

As always, the example code is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью