Thursday, August 8, 2024

Access specifiers (public, private, protected, default) in Java MCQ

 Here are multiple-choice questions (MCQs) on access specifiers (public, private, protected, default) in Java:


Question 1

Which access specifier allows members to be accessed from any other class?


A) private


B) protected


C) public


D) default


Answer: C) public


Question 2

Which access specifier restricts access to members within the same class only?


A) private


B) protected


C) public


D) default


Answer: A) private


Question 3

Which access specifier allows access to members within the same package and subclasses?


A) private


B) protected


C) public


D) default


Answer: B) protected


Question 4

What is the default access level when no access specifier is explicitly declared in Java?


A) private


B) protected


C) public


D) Package-private (default)


Answer: D) Package-private (default)


Question 5

Which of the following access specifiers can be applied to a class in Java?


A) public


B) private


C) protected


D) default


Answer: A) public


Question 6

Which access specifier can be used for a method that should only be accessible within its own class and not by any other class?


A) private


B) protected


C) public


D) default


Answer: A) private


Question 7

In which of the following cases can a protected member be accessed?


A) Within the same class only


B) Within the same package only


C) Within the same package and subclasses


D) From any class


Answer: C) Within the same package and subclasses


Question 8

Which of the following is not true about the private access specifier?


A) It can be applied to variables.


B) It can be applied to methods.


C) It can be applied to classes.


D) It restricts access to the defining class only.


Answer: C) It can be applied to classes.


Question 9

What will happen if a member variable is declared without any access specifier?


A) It will be private.


B) It will be protected.


C) It will be public.


D) It will have default (package-private) access.


Answer: D) It will have default (package-private) access.


Question 10

Which access specifier should be used for a method that can be overridden by any subclass but not accessible by objects outside of the package?


A) private


B) protected


C) public


D) default


Answer: B) protected


Question 11

What does the term "package-private" (default access) mean in Java?


A) Accessible only within the same class


B) Accessible only within the same package


C) Accessible by subclasses in other packages


D) Accessible from any class


Answer: B) Accessible only within the same package


Question 12

Which access specifier provides the least restrictive access?


A) private


B) protected


C) public


D) default


Answer: C) public


Question 13

What is the result of the following code snippet?


java

Copy code

class Example {

    private int num;

    public int getNum() {

        return num;

    }

    public void setNum(int num) {

        this.num = num;

    }

}

A) num can be accessed from any class.


B) num can only be accessed within the Example class.


C) num can be accessed from classes in the same package.


D) num can be accessed from subclasses.


Answer: B) num can only be accessed within the Example class.


Question 14

Which access specifier can be used to prevent other classes from accessing the num variable in the following code?


java

Copy code

public class Example {

    int num;

}

A) private


B) protected


C) public


D) default


Answer: A) private


Question 15

What does the following code demonstrate about access specifiers?


java

Copy code

class Parent {

    protected void display() {

        System.out.println("Protected method");

    }

}


public class Child extends Parent {

    public static void main(String[] args) {

        Child obj = new Child();

        obj.display();

    }

}

A) A protected method can be accessed from a subclass.


B) A protected method can be accessed from any class.


C) A protected method cannot be accessed from a subclass.


D) A protected method can only be accessed within the same package.


Answer: A) A protected method can be accessed from a subclass.


Question 16

Which access specifier allows a member to be accessed from within the same package but not by subclasses in other packages?


A) private


B) protected


C) public


D) default


Answer: D) default


Question 17

Which access specifier should be used if a class wants to expose a method to all classes in the package and all subclasses?


A) private


B) protected


C) public


D) default


Answer: B) protected


Question 18

Can a private method be overridden in Java?


A) Yes, in the same class.


B) Yes, in the subclass.


C) No, private methods cannot be overridden.


D) Yes, if it is declared as final.


Answer: C) No, private methods cannot be overridden.


Question 19

What is the main purpose of using access specifiers in Java?


A) To control the visibility of class members.


B) To improve the performance of the application.


C) To define the data types of class members.


D) To enforce the use of object-oriented programming.


Answer: A) To control the visibility of class members.


Question 20

In the following code, which access specifier can be used to make the display() method accessible only within the Example class?


java

Copy code

public class Example {

    void display() {

        System.out.println("Hello");

    }

}

A) private


B) protected


C) public


D) default


Answer: A) private

Encapsulation

 Encapsulation :

Encapsulation is the concept of wrapping data (variables) and methods (functions) into a single unit, typically a class.

It is a fundamental principle of object-oriented programming (OOP) that helps in hiding the internal state of an object and only exposing the necessary functionalities.

 

               //ex:   simple class is example for encapsulation

-//  data hiding can be done using private k/w

ex:

package AccesspecifiersInheritance;

class A1

{

               //  combining data and Methods in single unit is called Encapsulation

               //ex:   simple class is example for encapsulation

               //  data hiding can be done using private k/w

               int a=10;

               private int b=20;//  can be accessed only in class - A1 but not outside class

               void M1()

               {

                              System.out.println("Calling M1");

               }

}

package Inheritance;

public class Encapsulation

{

               public static void main(String[] args)

               {

                              //create obj for class- A1

                              A1 a1ref = new A1();

                             

                              // access private variable

                              a1ref.b //  using private var-We can perform data hiding

               }

}

Access Specifiers

 Access Specifiers :

specifies the access level of variables, Methods , classes.

the four main access specifiers in Java are:

·        public

·        private

·        protected

·        default(no keyword)

Package1

  ── Class A

  └── Class B

 

Package2

  ── Class C

  └── Class D

 

---------------------------------------------------------------------------------------------------

                                            Package-1                                              Package-2

                                             Class- A   class -B                             Class -C class- D

---------------------------------------------------------------------------------------------------

public                                   yes            yes                                   yes           yes 

private                                yes            No                                   No            No

protected                            yes             yes                                  yes(Inheritance)   Yes  (Inher)

Default                                yes             yes                                 No          No        

 

public: Variables and methods declared as public can be accessed from any class, regardless of the package.

private: Variables and methods declared as private can only be accessed within the same class and are not accessible outside of it.

default: (No specifier) Variables and methods with default access can only be accessed within the same package and are not accessible from classes in other packages.

protected: Variables and methods declared as protected can be accessed within the same package and in subclasses in other packages through inheritance.

 

package PackageOne;

public class A

{

               //define public variable  pubid=10 ;

               public    int a =10;// //  public var

               public int pubid = 10;

              

               //define private variable,  prVariable =3.45f

               private float prVariable = 3.45f;// private var

               //define protected  variable protCar=34;

               protected  int protVariable  = 34;// protected variable ---> Inheritance

              

               //define def variable  defVariable =50;

//`          default defVariable =  50;// Invalid // error

               int defVariable  = 50; //  def Var

               // if we dont write any access specifiers public, private,protected, then it is def variable

               // Default var    

               // 2 Access specifiers are appplicable for variables and Methods, Constr,class

               // Define public method M1()     

               public void M1()//// public method

               {

                              System.out.println("Calling public M1()");

               }

               public static void main(String[] args)

               {

                              // create obj for class -A

                              A aref =  new A();

                             

                              System.out.println("acesssing public variable " + aref.pubid);

                              System.out.println("acesssing private variable " +  aref.prVar);

                              System.out.println("acesssing protected variable "+ aref.protVar);

                              System.out.println("acesssing default variable "+ aref.defVar);

               }

}

------------------

package PackageOne;

public class B {

               public static void main(String[] args) {

                              // create obj for class -A

                              A aref = new A();

                             

                              System.out.println("acesssing public variable "+ aref.pubid); //10

//                           System.out.println("acesssing private variable "+ aref.prVar);

                              // error :The field A.prVariable is not visible

                              // Private variable can be accesseed  inside the same class but not outside class

                              // Private variables  canot be accessed from classes - B,C,D

                              System.out.println("acesssing protected variable "+aref.protVar);//34

                              System.out.println("acesssing default variable "+ aref.defVar);//50

               }

}

--------------------

package PackageTwo;

import PackageOne.A;

public class C extends A

{//extends A

                                                                           // get copy of parent class variable from class -A

               public static void main(String[] args)

               {

                              // TODO Auto-generated method stub

                              // create obj for class -A

                              A aref = new A();

                             

                                                            System.out.println("acesssing public variable "+ aref.pubid);// accessed any wheere

                                                           

//                                                         System.out.println("acesssing private variable "+  aref.prVar); ///  canot be accseesed

                                                           

//                                                         System.out.println("acesssing protected variable "+ aref.protVar); // ????? 

                                                            //  The field A.protCar is not visible

                                                            // Note : if we want to access protected variable  from other packages -

                                                            //we must use inhertiance

                                                           

                                             // create obj for class -C

                                                            C cref = new C();

                                                           

                                                            System.out.println("acesssing protected variable "+ cref.protVar);//34

//                                                         System.out.println("acesssing def variable "+ aref.defVar);

                                                            // The field A.defVariable is not visible

                                                            // Default access specifier scope is package level

                                                            //   def variable - can be accessed inside same package only  but not oustide of the package

                                                            //  C class is defined in pakcageTwo

                                                           

//                                                         System.out.println("acesssing protected variable "+ cref.defVar);//error

                                                                                         

               }

}

-----------------------------

package PackageTwo;

public class D {

               public static void main(String[] args) {

                              // TODO Auto-generated method stub

               }

}

HW Declare Public, private , protected, default 'varaibles' in   class1 ,  check access level of variables in side Classes - class2,class3,class4..

   packageA              PackageB

Class1  class2            class3   class4

HW  Declare Public, private , protected, default 'Methods' in   class1 ,  check  these methods can be accessed from class2,class3 ..?

 

Access Specifiers in Inheritance

In Java, access specifiers control the visibility and accessibility of members (variables and methods) of a class, especially when dealing with inheritance.

Here’s how each access specifier behaves in the context of inheritance:

 

package AccesspecifiersInheritance;

class A

{

               public int pubid;

               private int privateVar;

               protected int protectedVar;

               int defVar;

              

}

check above variables - can be accessed in the child class

package Inheritance;

public class TestaccessspecifiersInheritance extends A

{

                 // extends A

                 //   getting parent class variable and parent class methods into child class

                              public static void main(String[] args) {

                                             // create obj for class- TestaccessspecifiersInheritance()

                                             TestaccessspecifiersInheritance tref = new TestaccessspecifiersInheritance();

                                             System.out.println("public var" + tref.pubid);

                                             System.out.println("private var"+ tref.privateVar);// 

                                             // Error :Private variable is not visible in other classses

                                             // We cannot access private variable  in other classes except Class-A

                                            

               //  private variables --  cannot be inherited as we can access private variable inside the same class where we declared private  but from out side the class

                                             System.out.println("protected var"+tref.protectedVar);

                                             System.out.println("default var"+ tref.defVar);

               //  if we use inheritance,  we can get parent class -   public , protected, default

//                public variables , protected , default  var's can be inherited

                                             // Private var's cannot be inherited

                              }

               }

Note:

FAQ Privates variables are inherited or not ?

No. Private variables cannot be inherited  as we  cannot access from outside class

Refer:

https://www.sitesbay.com/java/java-access-modifiers

HW Define some public, private, protected, default -' methods',   check we can access these methods in child class using inheritance?

Object class

Object class:

// Although you don't see this explicitly in most classes,

// every class in Java extends Object by default.

class Object

{

    // Some methods available in Object class:

    // - toString()

    // - equals(Object obj)

    // - hashCode()

    // - getClass()

    // - clone()

}             

Object is a predefined class in Java. It is the root of the class hierarchy. Every class in Java implicitly extends the Object class if no other superclass is specified

FAQ: What is the superclass of all classes in Java?

The Object class is the superclass (also known as the parent or base class) for all classes in Java.

class A extends Object

{

    // Since A doesn't extend any other class,

    // it automatically extends Object.

}

 

class String extends Object {

    // String class, like any other class,

    // ultimately extends Object.

}                            

FAQ:  What is object class and when should we use object class?

·  indirectly inherits from the Object class. It is the superclass for all classes in Java.

·  Since Object is the ultimate parent class, it provides several fundamental methods that are inherited by all Java classes, such as:

  • toString(): Returns a string representation of the object.
  • equals(Object obj): Compares the current object with another object for equality.
  • hashCode(): Returns a hash code value for the object.
  • getClass(): Returns the runtime class of the object.
  • clone(): Creates and returns a copy of the object (if the class implements the Cloneable interface).
  • finalize(): Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Ex:

// An Object reference variable can store references to any type of object,

// including instances of Integer, Float, String, etc.

// Example: Storing an int value in an Object reference variable

 

Object obj;

 

// Boxing: Storing an int value in an Object reference variable

obj = 10; // int value is automatically boxed into an Integer object

 

// Boxing: Storing a float value in an Object reference variable

obj = 10.5f; // float value is automatically boxed into a Float object

 

// Storing a String value in an Object reference variable

obj = "Hello, World!";

 

an Object reference variable can store different types of values, including primitive values through autoboxing:

Explanation

In Java, the Object class is the root of the class hierarchy. This means that an Object reference variable can refer to an object of any class, including instances of wrapper classes like Integer, Float, and String.

 

When you assign a primitive value to an Object reference, Java automatically converts the primitive value into its corresponding wrapper class object through a process called autoboxing.

            +-------------------+       +-------------+

            |   Object ref var   |----->|  Integer(10) | (Boxing: int to Integer)

            |      obj           |       +-------------+

            +-------------------+

                      |

                      |                 +-------------+

                      |---------------> |  Float(10.5) | (Boxing: float to Float)

                      |                 +-------------+

                      |

                      |                 +-------------+

                      |---------------> | "Hello"      | (String is already an object)

                                        +-------------+

 

·  Storing an int value:

  • When you assign an int value like 10 to obj, Java performs autoboxing, converting the int to an Integer object. Now, obj holds a reference to this Integer object.

·  Storing a float value:

  • Similarly, when you assign a float value like 10.5f to obj, it is autoboxed into a Float object. Now, obj holds a reference to this Float object.

·  Storing a String value:

  • When you assign a String value like "Hello" to obj, it directly holds a reference to the String object, as String is already an object type.

 

 

package InterfaceBasics;

public class TestObjectClassReferenceVariable {

               public static void main(String[] args)

               {

                              int i= 10;

                              float f=10.85f;   

                              // object ref variable , we can store int value, float value, String value

                              // store int value in obj ref variable

                              Object oref = i;

                              //            10

                              //   oref=  10

                              System.out.println("object can store int val="+oref);

                              // store float value in obj ref var

                              oref = f;

                              //     10.85

                              //  oref =  10.85

                              System.out.println("object can store float val="+ oref);

                              // store String value in obj ref var

                              oref = "Ram";

                             

                              System.out.println("object can store String val="+oref);

                              // By using Object variable,  we can store any type of value

                             

                              //when we want to store any data type val, we will go for Object class.

                              // HW store char value in obj ref variable and display it

                              // HW store boolean value in obj ref variable and display it

               }

}

                             

Object array:

package InterfaceBasics;

public class TestObjectClass {

               public static void main(String[] args)

               {

                              int a [] = {10,20 ,30};

                              float farr[] = {2.4f,3.5f,4.5f};

                              char charr [] = {'A','B','C'};

                             

                              // Using object arr -   1 int  + 1 float +  1 char ....etc

                              // define obj arr - store  {10, 2.4f,'A', "Ramu"};

                              Object oarr [] = {10 ,2.4f,'A',"Ramu"};

//(or )

               // create object array using new  k/w with size =5

                              Object oarr2 [] =  new Object [5];//  0 to size-1 i.e o  to 5-1=4

                             

                              // store  10 value at index no=0

                              oarr2[0] = 10;

                              // store  2.3f value at index no=1

                              oarr2[1] = 2.3f;

                              // store  'A' value at index no=2

                              oarr2[2] = 'A';

                              // store  "Ram" value at index no=3

                              oarr2[3] = "Ram";

                              // store   true value at index no=4

                              oarr2[4] =  true;

                             

                              // get all values from Object array using 2 ways

                              // HW 1 . display all values using for loop with index no

                                                           

                              // HW 2 display Object array values using 'for each' loop  ?                                         

               }

}

 

git commands MCQ

 Here are some multiple-choice questions (MCQs) on Git commands relevant for Selenium: 1. Which Git command is used to clone a remote reposi...