Showing posts with label protected. Show all posts
Showing posts with label protected. Show all posts

Friday, 14 May 2021

Php: Access specifiers (or) visibility modifiers

 

Access specifiers (or) visibility modifiers are used to control the access to properties, methods of an object.

 

Php support 3 access modifiers.

a.   public: Any property/method defined with this access modifier can be accessed from anywhere.

b.   protected: Any property/method defined with this access modifier can be accessed from this class and its subclasses.

c.    Private: Any property/method defined with this access modifier can be accessed within the class only.

 

 

How to define a method with access specifiers?

‘public’, ‘protected’ and ‘private’ keywords are used to define methods with controlled access. Just prepend the method with access specifiers.

 

Example

public function m1(){

 

}

 

Let’s define a class with

a.   One private method.

b.   One public method

c.    One protected method

class ParentClass{

    public function i_am_public(){
        echo "\nIn public method";
    }

    protected function i_am_protected(){
        echo "\nIn protected method";
    }

    private function i_am_private(){
        echo "\nIn private method";
    }
}

 

Since ‘i_am_public()’ method is defined with public access specifier, you can access it outside the class, but not others.

 

$p1 = new ParentClass();

$p1->i_am_public();

 

But when you try to access protected, private methods via object from outside of the class, you will get an error.

 

As I said earlier, you can access a protected method from subclass.

class ChildClass extends ParentClass{

    function call_super_class_methods(){
        $this->i_am_public();
        $this->i_am_protected();
        // $this->i_am_private(); Do not run
    }
}

 

You can access both public and protected methods from sub class, but not the private methods.

 

Find the below working application.

 

access_specifiers_demo.php

 

#!/usr/bin/php

<?php

    class ParentClass{

        public function i_am_public(){
            echo "In public method\n";
        }

        protected function i_am_protected(){
            echo "In protected method\n";
        }

        private function i_am_private(){
            echo "In private method\n";
        }
    }

    class ChildClass extends ParentClass{

        function call_super_class_methods(){
            $this->i_am_public();
            $this->i_am_protected();
            // $this->i_am_private(); Do not run
        }
    }

    $p1 = new ParentClass();
    $p1->i_am_public();
   // $p1->i_am_protected(); Do not run
   // $p1->i_am_private();  Do not run

    $c1 = new ChildClass();
    $c1 -> call_super_class_methods();

?>

 

Output

$./access_specifiers_demo.php 

In public method
In public method
In protected method

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Tuesday, 6 February 2018

Kotlin: Access specifiers

Access specifiers are used to restrict the data access. Kotlin support 4 access specifiers.
a.   private
b.   protected
c.   internal
d.   public

If you do not specify any access specifier, then public is used by default.

Where can I apply access specifiers?
You can apply access specifiers on Classes, interfaces, constructors, objects, functions, properties and their setter methods. Getters always have the same visibility as the property.

Below table summarizes the access specifiers.
Access Specifier
Description
Private
Members defined with private access specifier are visible only in same scope.
Protected
Members defined with protected access specifier are visible in the same class and all the sub classes of this class.
Internal
Members defined with internal access specifier are visible in the same module.
Public
Members defined with public access specifier are visible from everywhere.

public access specifier
If you mark an element with public modifier, then this element can be accessed from anywhere. If you do not specify any access modifier to an element, the access is public by default.

Test.kt
package com.sample.model

class Test {
 public var i : Int = 10
 var j : Int = 11
}

HelloWorld.kt
import com.sample.model.Test

fun main(args: Array<String>) {
 var obj = Test()

 println("i = ${obj.i}")
 println("j = ${obj.j}")

 obj.i = 88
 obj.j = 99

 println("i = ${obj.i}")
 println("j = ${obj.j}")

}

Output

i = 10
j = 11
i = 88
j = 99

private access specifier
If you declare an element using private access specifier, then the code that is declared in the same scope can access it, no other code can access it.


Test.kt
package com.sample.model

private var totalObjs: Int = 0

class DemoClass1 {
 constructor() {
  totalObjs++
 }

 companion object {
  fun getTotalObjs() = totalObjs
 }
}

class DemoClass2 {
 constructor() {
  totalObjs++
 }
}

HelloWorld.kt
import com.sample.model.*

fun main(args: Array<String>) {
 var obj1 = DemoClass1()
 var obj2 = DemoClass2()

 println("Total objects created : ${DemoClass1.getTotalObjs()}")

 var obj3 = DemoClass1()
 var obj4 = DemoClass2()

 println("Total objects created : ${DemoClass1.getTotalObjs()}")
}

Output
Total objects created : 2
Total objects created : 4

Protected access specifier
Members defined with protected access specifier are visible in the same class and all the sub classes of this class.


Test.kt

open class DemoClass1 {
 protected var i: Int = 10
}

class DemoClass2 : DemoClass1() {
 fun getValueOfI(): Int {
  return i
 }
}

Note
If you override a protected member and do not specify the visibility explicitly, the overriding member will also have protected visibility.

internal access specifier
Members defined with internal access specifier are visible in the same module. A module is a collection of kotlin resources compiled together.


Test.kt

open class DemoClass1 {
 internal var i: Int = 10
}

class DemoClass2 : DemoClass1() {
 fun getValueOfI(): Int {
  return i
 }
}

Note

a.   Local variables, local functions and classes do not have access specifiers



Previous                                                 Next                                                 Home

Wednesday, 19 February 2014

Overriding Methods

A subclass has the same instance method signature like the super class instance method is called overriding.

Example
class Animal{
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 void print(){
  System.out.println("I am Tiger");
 }
}

As you observe, the classes Animal and Tiger has the same method signature print(). So print method in the class Tiger overrides the method in the class Animal.

Dynamic Method Dispatch
It is a mechanism, where a call to the overridden method is resolved at run time. It is also called as run time polymorphism.

Take the same examples Animal and Tiger.
class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.print();
 }
}

Output
I am Tiger

As you see the statement
     Animal anim1 = new Tiger();

An object of the Tiger class is assigned to the Animal reference variable. This is completely correct in Java. We can assign a subclass object to super class reference variable.

When the program calls the print(), then at run time JVM checks, the actual object pointed by the reference variable and calls the respective method of the actual object. So it calls the print method in the Tiger class.

Modifiers
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

Some points to Remember
1. Is run time polymorphism applicable to static methods also ?
No, static methods can't be overridden, they just hide the static method of the super class.

2. Is the instance variables overridden ?
No
class Animal{
 String str = "Animal";
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 void print(){
  System.out.println("I am Tiger");
 }
}
    
class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.print();
  System.out.println(anim1.str);
 }
}
   
Output
I am Tiger
Animal

If the instance variables are overridden, then the output should print the message “Tiger”. I.e, instance variables are just hide the instance variables of super class, these can't be overridden.

3. Can I apply static modifier to the subclass overriding method?
No, compiler throws an error.
 
 Example       
class Animal{
 String str = "Animal";
 
 void print(){
 System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 
 static void print(){
  System.out.println("I am Tiger");
 }
}
   
When tries to compile the Tiger class, below error thrown.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
static void print(){
^
overriding method is static
1 error

4. What is wrong with the below program ?    
class Animal{
 String str = "Animal";
 
 void print(){
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 String str = "Tiger";
 
 private void print(){
  System.out.println("I am Tiger");
 }
}


When you tries to compile the above program, compiler throws the “Weaker access specifier error”

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
private void print(){
^
attempting to assign weaker access privileges; was package
1 error

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a default instance method in the superclass can be made public, protected, default, but not private, in the subclass.

5. What is the difference between static binding and Dynamic binding ?
Static binding occurs at compile time, where as Dynamic binding at run time. Dynamic method dispatch is an example for Dynamic binding.

6. What is wrong with the below program ?
class Animal{
 String str = "Animal";
 
 void print(){
  System.out.println("I am animal");
 }
}
  
class Tiger extends Animal{
 String str = "Tiger";

 void print()throws Exception{
  System.out.println("I am Tiger");
 }
}

The overriding method cannot throw any exceptions that are not thrown by the overridden method.

When you tries to compile the above program compiler throws the below error.

Tiger.java:3: error: print() in Tiger cannot override print() in Animal
void print()throws Exception{
^
overridden method does not throw Exception
1 error

7. Is the constructors inherited ?
A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses.

8. When a subclass object assigned to super class reference variable, then the reference variable can call the methods which are defined in the super class, trying to call the methods which are not defined in super class cause the compile time error.

Example
class Animal{
 void print()throws Exception{
  System.out.println("I am animal");
 }
}

class Tiger extends Animal{
 void print(){
  System.out.println("I am Tiger");
 }

 void show(){
  System.out.println("I am show method");
 }
}

class DynamicMethodDispatchEx{
 public static void main(String args[]){
  Animal anim1 = new Tiger();
  anim1.show();
 }
}
    
When you are trying to compile the program, below error thrown, since the reference variable of class Animal, “anim1” trying to call the method “show: which is not defined in the class “Animal”.

DynamicMethodDispatchEx.java:5: error: cannot find symbol
anim1.show();
^
symbol: method show()
location: variable anim1 of type Animal
1 error

9. Can I specify weaker access specifier to the overriding method in the sub class ?
No


Multi path inheritance                                                 Covariant return type                                                 Home

Friday, 7 February 2014

How to define a method

A method is a programmed procedure that is defined as part of a class. A class (and thus an object) can have more than one method.

Syntax of method definition
    modifier returnType methodName(parameters) Exception List{
        Method Body
    }

Method definition composed of six components :

modifiers : like private, public, protected or default. We have already seen private, public and default. Will discuss more about these in the packages section.

ReturnType : The type of the value written by the method. If you don't want to return any value make the return type as void. Return type will be any primitive type or reference type.

MethodName : The name given to the method

parameters: Method is defined with parameters or with out parameters. A method can be defined with any number of parameters.

Exception List: A Method can throw any number of exceptions, will discuss about this on ExceptionHandling section

Method Body: The actual implementation of the method goes here

Example
    1. public int sum(int a, int b){
        return (a+b);
        }

        modifier : public
        returnType : int
        methodName : sum
        parameters : a,b
        Exception List : none
        Method body : calculates the sum of the two parameters and return the sum.

2. void sayHello(){
        System.out.println(“Hello”);
    }

    modifier : default
    returnType : void
    methodName : sayHello
    parameters :none
    Exception List : none
    Method body : simply prints the message “Hello” to the console.

If no access specifier (modifier) specified to a variable or method, it assumes default access specifier(modifier).

Naming a Method
By convention method names starts with a small character and starting character of subsequent words is capitalized.

    Example:
    walk()
    sleep()
    setColor(String s)
    getHeight()

Local Variables
Variables declared inside a method are called local variables. These are not accessible out side of the method. You must initialize local variables before using.

Some Points to remember
Trying to use local variables before initializing causes compile time error

Example
class LocalVariable{
 int sum(int a, int b){
  int c;
  System.out.println(c);
  return (a+b);
 }
} 

Since “c” is a local variable, when your program tries to access local variable, before initialization, compiler will throw the error.
 
For the above program, you will get below error
LocalVariable.java:5: error: variable c might not have been initialized
            System.out.println(c);
                                          ^
1 error





Instance methods                                                 More about methods                                                 Home

Thursday, 6 February 2014

Instance variables

Instance variables are those which are associated with object. Person object personA has instance variables height, weight, color, country.

Instance variables are also called member variables or fields.

Fields declaration syntax
modifier dataType variableName;

Field declaration composed of three components
     1. modifier is any one of public, private, protected, default.
    2. dataType is any primitive or reference type
    3. name of the variable
Example:
private int var;
    we will discuss about the access modifiers private and public in this section.

Access Modifiers (public, private)
private : the field is accessible only within its own class.
Example consider the class Person. I given private access to instance variables height, weight, color and country. So any method which is defined inside the class Person can able to access these variables, but you can't access outside the class.
class Person{
 private float height, weight;
 private String color, country;

 float getHeight(){
  return height;
 }

 float getWeight(){
  return weight;
 }

 String getColor(){
  return color;
 }

 String getCountry(){
  return country;
 }
}
What happen if I tried to access the private variables outside of my class ?
Good Question, You will get compile time error.

Trying to access the private variables from other class PersonTest.
class PersonTest{
 public static void main(String args[]){
  Person personA = new Person();
  personA.height = 6;
 }
}

When you try to compile the above code, you will get the compiler error like below
 PersonTest.java:6: error: height has private access in Person
           personA.height = 6;
           ^
           1 error
    

Then how to solve this problem
Update the Person class by providing setter methods, to set the private properties.
class Person{
 private float height, weight;
 private String color, country;

 void setHeight(float h){
  height = h;
 }

 void setweight(float w){
  weight = w;
 }

 void setColor(String c){
  color = c;
 }

 void setCountry(String o){
  country = o;
 }

 float getHeight(){
  return height;
 }

 float getWeight(){
  return weight;
 }

 String getColor(){
  return color;
 }

 String getCountry(){
  return country;
 }
}
            
As you see in the above class Person, it is updated by adding 4 setter methods like setHeight, setWeight, setColor, setCountry to set the private properties height, weight, color, country respectively.

Update the PersonTest class also like below
class PersonTest{
 public static void main(String args[]){
  Person personA = new Person();
  Person personB = new Person();

  /* Setting properties for personA object */
  personA.setHeight(6);
  personA.setweight(75);
  personA.setColor("White");
  personA.setCountry("India");

  /* Setting properties for personB object */
  personB.setHeight(5.5f);
  personB.setweight(76);
  personB.setColor("Black");
  personB.setCountry("America");

  /* Calling the behaviors and printing the details of personA */
  System.out.println("PersonA Height is " + personA.getHeight());
  System.out.println("PersonA Weight is " + personA.getWeight());
  System.out.println("PersonA color is " + personA.getColor());
  System.out.println("PersonA country is " + personA.getCountry());
  System.out.println();

  /* Calling the behaviors and printing the details of personB */
  System.out.println("PersonB Height is " + personB.getHeight());
  System.out.println("PersonB Weight is " + personB.getWeight());
  System.out.println("PersonB color is " + personB.getColor());
  System.out.println("PersonB country is " + personB.getCountry());
 }
}
  
Output
PersonA Height is 6.0
PersonA Weight is 75.0
PersonA color is White
PersonA country is India

PersonB Height is 5.5
PersonB Weight is 76.0
PersonB color is Black
PersonB country is America
  

public modifier
    the field is accessible from all classes.

Some points to remember

1. If you don't initialize an instance variable, by default it is initialized to default value.
Data Type Default Value
int 0
float 0
String Null
boolean FALSE
Reference type null

Example
class DefaultValue{
 byte byteVar;
 short shortVar;
 int intVar;
 long longVar;
 char charVar;
 float floatVar;
 double doubleVar;
 boolean boolVar;
 String stringVar;

 public static void main(String args[]){
  DefaultValue obj = new DefaultValue();
  
  System.out.println("byte variable is set to " + obj.byteVar);
  System.out.println("short variable is set to " + obj.shortVar);
  System.out.println("int variable is set to " + obj.intVar);
  System.out.println("long variable is set to " + obj.longVar);
  System.out.println("char variable is set to " + obj.charVar);
  System.out.println("float variable is set to " + obj.floatVar);
  System.out.println("double variable is set to " + obj.doubleVar);
  System.out.println("bool variable is set to " + obj.boolVar);
  System.out.println("string variable is set to " + obj.stringVar);
 }
}
     
Output
byte variable is set to 0
short variable is set to 0
int variable is set to 0
long variable is set to 0
char variable is set to
float variable is set to 0.0
double variable is set to 0.0
bool variable is set to false
string variable is set to null
     

Object Creation                                                 Encapsulation                                                 Home