This question is related to java If you dont specify an acce

This question is related to java:

If you don\'t specify an access modifier when you declare a member field of a class, what does Java assign it? Also, specify the accessibility limit of protected specifier. Demonstrate your answer by providing minimal Java examples that will and will not compile, as appropriate.

Solution

default Access modifier:-

If we don\'t assign an access modifier when you declare a member field of a class, Java assigns default keyword to it.

If a A member field declared without any access modifier,it is available to any other class in the same package.

Example:-

String version = \"1.1\";

A member variable that is declared private can only be accessed within the declared class itself.


Private Access modifier:-

Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if public getter and setter methods are present in the class.

Example:-

public class Name {
   private String myName;

   public String getName() {
      return this.myName;
   }

   public void setName(String myName) {
      this.myName= myName;
   }
}

Here, the myName variable of the Name class is private, so there\'s no way for other classes to retrieve or set its value directly.

So, to make this variable available to the outside world, we defined two public methods: getName(), which returns the value of myName, and setName(String), which sets the value of myName.


Protected Access Modifier:-

member variables which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members\' class.

Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.


Example:-

class Player {
   protected boolean openSpeaker(Speaker sp{
}
}

class AudioPlayer extends Player {
   boolean openSpeaker(Speaker sp) {
      // implementation details
   }
}

Here we can override the openSpeaker() function because it used protected access modifier.
if we mentioned private, there is no way to override the openSpeaker() function.

This question is related to java: If you don\'t specify an access modifier when you declare a member field of a class, what does Java assign it? Also, specify t
This question is related to java: If you don\'t specify an access modifier when you declare a member field of a class, what does Java assign it? Also, specify t

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site