Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Protected Variable

Posted By: Cadencia Bernard     Category: Java     Views: 31971

This article explains about protected variable in java with example.

Protected variable can be accessed only by code in a subclass or the same package.

Syntax of Protected Variable

protected type varName = value; 

type is any data type in java.
varName is any valid identifier in java. It is a variable name.
value is an optional. You can initialize variable by assigning its value. 

Example of Protected Variable

Example 1 : Program that illustrates protected variable use in java using shape class 

public class Shape
   protected int sides; 

   public Shape() 
     sides = 3; 

   public int getSides() 
     return sides; 

   public printSides() 
      System.out.println("This object has " + sides + " sides." );

public class Square extends Shape
  public Square(int nSides) 
    sides = nSides;  // dont need to call super class constructor due to protected type of variable.

class ProtectedVariableDemo
   public static void main(String args[])
       Square sObj = new Square(10);



This object has 10 sides.


Didn't find what you were looking for? Find more on Protected Variable Or get search suggestion and latest updates.

Cadencia Bernard
Cadencia Bernard author of Protected Variable is from Paris, France.
View All Articles

Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

No Comment Found, Be the First to post comment!