Home > Java > Classes > Public Access Specifier > Introduction
Introduction

Introduction to Public Access Specifier

Public keyword is used to specify classes, data members (also called variables) and methods as public . The public classes, data members and methods can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, this public class represents the application. You use public classes, methods, or fields only if you explicitly want to offer access to these entities and if this access cannot do any harm.


Syntax


//public class
public class MyClass {
    //public data members
    public int age;
    //public constructor
    public MyClass() { }
    //public method
    public void show() {}
}


Example


1.   /**
2.   * @(#)Cat.java
3.   *
4.   *
5.   * @author
6.   * @version 1.00 2009/11/16
7.   */
8.
9.   public class Cat {
10.
11.    //Data members with public access
12.    public String name;
13.    public String color;
14.    
15.        
16.                
17.    /**
18.     * Creates a new instance of Cat.
19.     */
20.  public Cat() {
21.   }
22.
23.    public String getName() {
24.        
25.        return name;
26.    }   
27.        
28.    public String getColor() {
29.        
30.        return color;
31.    }   
32.
33.    /**
34.     * @param args the command line arguments
35.     */
36.    public static void main(String[] args) {
37.        // TODO code application logic here
38.        
39.        Cat cat = new Cat();
40.        
41.        cat.name = "July";
42.       cat.color = "White";
43.
44.        System.out.println("Cat Information:");        
45.        System.out.println("Name: "+ cat.getName());        
46.        System.out.println("Color: "+ cat.getColor());
47.        
48.    }
49. }


Output


Cat Information:
Name: July
Color: White

Leave a Reply

Fields with * are mandatory.
* Name:
Website:
* Comments:
 
Tags allowed: <strong> <i> <u>
* Code:
 
 
Submit   Cancel