Java: Accessing object members

This entry is part 22 of 54 in the series Learn Java

In addition to creating the object, the members of the class that are to be accessible beyond their package need to be declared as public in the class definition.

The members of this object can now be reached by using the dot operator after the instance name.

In this example, the members of the object MyRectangle are x, y and getArea().

package javaapplication19;

public class JavaApplication19 {

    static class MyRectangle {
        public int x, y;
        
        public int getArea() {
            return x * y;
        }
    }

    public static void main(String[] args) {
        MyRectangle r = new MyRectangle();      
        r.x=10;
        r.y=5;
        int area = r.getArea();
        System.out.println(area);      
    }
}

 

 

 

PHP & OOP: Visibility

This entry is part 9 of 11 in the series PHP & OOP

The visibility of a property or method can be defined by the keywords public, protected or private.

Property (variable) visibility

Class members declared public can be accessed everywhere.

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

Members declared as private may only be accessed by the class that defines the member.

Lets look at the example below.

<?php

class MyClass
{
    public $public_str = 'I am a public string';
    protected $protected_str = 'I am a protected string';
    private $private_str = 'I am a private string';

    function printString()
    {
        echo $this->public_str . "<br>";

        echo $this->protected_str . "<br>";
        echo $this->private_str . "<br>";
    }
}

$obj = new MyClass();
$obj->printString(); // Shows Public, Protected and Private, pringString() is a public function
echo "<br>";
echo $obj->public_str; // Works
// echo $obj->protected; Fatal Error as $protected is accessed outside the class and not by an inherited class
// echo $obj->private; Fatal Error as $private is accessed outside the class

?>

The 3 member variables $public_str, $protected_str, $private_str can be assessed using the function printString() as it is a member function

printString() is a public function and so you can access it to print out the 3 variables.

$obj->protected_str:  This will produce a fatal error as $protected is accessed outside the class and not by an inherited class

$obj->private_str:  This will generate a fatal error as $private is accessed outside the class.