Java Class
In Java everything is encapsulated under classes. Class is the core of Java language. It can be defined as a template that describe the behaviors and states of a particular entity.
A class defines new data type. Once defined this new type can be used to create object of that type.
In Java, to declare a class class keyword is used. A class contain both data and methods that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods. Thus, the instance variables and methods are known as class members.
Rules for Java Class
A class can have only public or default(no modifier) access specifier. It can be either abstract, final or concrete (normal class).
It must have the class keyword, and class must be followed by a legal identifier.
It must have the class keyword, and class must be followed by a legal identifier.
It may optionally extend only one parent class. By default, it extends Object class.
The variables and methods are declared within a set of curly braces.
Java class Syntax
class class_name
{
field;
method;
}
A simple class example
Suppose, Student is a class and student's name, roll number, age are its fields and info() is a method. Then class will look like below.
class Student
{
String name;
int rollno;
int age;
void info()
{
// some code
}
class class_name
{
field;
method;
}
A simple class example
Suppose, Student is a class and student's name, roll number, age are its fields and info() is a method. Then class will look like below.
class Student
{
String name;
int rollno;
int age;
void info()
{
// some code
}
}
className variable_name = new className();
Here, className is the name of class that can be anything like: Student that we declared in the above example.
variable_name is name of reference variable that is used to hold the reference of created object.
This is how a class look structurally. It is a blueprint for an object. We can call its fields and methods by using the object.
The fields declared inside the class are known as instance variables. It gets memory when an object is created at runtime.
Methods in the class are similar to the functions that are used to perform operations and represent behavior of an object.
Java ObjectObject is an instance of a class while class is a blueprint of an object. An object represents the class and consists of properties and behavior. Object is an instance of class. You may also call it as physical existence of a logical template class.
Properties refer to the fields declared with in class and behavior represents to the methods available in the class. In real world, we can understand object as a cell phone that has its properties like: name, cost, color etc and behavior like calling, chatting etc. So we can say that object is a real world entity. Some real world objects are: ball, fan, car etc.
Syntax to create an objectclassName variable_name = new className();
Here, className is the name of class that can be anything like: Student that we declared in the above example.
variable_name is name of reference variable that is used to hold the reference of created object.
The new is a keyword which is used to allocate memory for the object.
There are many other ways by which we can create object of the class.
There are many other ways by which we can create object of the class.
Ex: Creation of object
Student std = new Student();
Here, std is an object that represents the class Student during runtime.
The new keyword creates an actual physical copy of the object and assign it to the std variable.
It will have physical existence and get memory in heap area.
The new operator dynamically allocates memory for an object.
public class Student
{
String name;
int rollno;
int age;
void info()
{
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args)
{
Student std = new Student();
// Accessing and property value
std.name = "Ravi";
std.rollno = 253;
std.age = 25;
// Calling method
std.info();
}
}
Output:
I:\>javac Student.java
I:\>java Student
Name: Ravi
Roll Number: 253
Age: 25
I:\>javac Student.java
I:\>java Student
Name: Ravi
Roll Number: 253
Age: 25
In this example, we created a class Student and an object. Here you may be surprised of seeing main() method but don’t worry it is just an entry point of the program by which JVM starts execution. Here, we used main method to create object of Student class and access its fields and methods.
Note: In case, if we don’t initialized values of class fields then they are initialized with their default values.
Default values of instance variables
int, byte, short, long → 0
float, double → 0.0
string or any reference = null
boolean → false
These values are initialized by the default constructor of JVM during object creation at runtime.
Program to illustrate this and super Keyword:
class PrgOnThis
{
int a=10;
}
class B extends PrgOnThis
{
int a=20;
void show(int a)
{
System.out.println(a);// 30
System.out.println(this.a);// 20
System.out.println(super.a);// 10
}
public static void main(String[] args)
{
B obj = new B();
obj.show(30);
}
}
Output:
C:\Users\student\Desktop>javac B.java
C:\Users\student\Desktop>java B
30
20
10
Java Access Modifiers
Access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and the setter methods.
Ex:
class Animal{
public void method1() {...}
private void method2() {...}
}
In the above example, we have declared two methods:
method1() and method2().
method1 is public - This means it can be accessed by other classes.
method2 is private - This means it cannot be accessed by other classes.
Note the keyword public and private. These are access modifiers in Java. They are also known as visibility modifiers.
Types of Access Modifier
There are four access modifiers keywords in Java and they are:Modifier Description
Default declarations are visible only within the package (package private)
Private declarations are visible within the class only
Protected declarations are visible within the package or all subclasses
Public declarations are visible everywhere
Default declarations are visible only within the package (package private)
Private declarations are visible within the class only
Protected declarations are visible within the package or all subclasses
Public declarations are visible everywhere
Default Access Modifier
If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default the default access modifier is considered.
If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default the default access modifier is considered.
For example,
package defaultPackage;
class Logger
class Logger
{
void message()
{
System.out.println("This is a message");
}
}
Private Access Modifier
void message()
{
System.out.println("This is a message");
}
}
Here, the Logger class has the default access modifier. And the class is visible to all the classes that belong to the defaultPackage package. However, if we try to use the Logger class in another class outside of defaultPackage, we will get a compilation error.
Private Access Modifier
When variables and methods are declared private, they cannot be accessed outside of the class.
For example,
class Data
{
// private variable
private String name;
private void display()
{
System.out.println("The name is"+name);
}
}
public class Main
{
public static void main(String[] main)
{
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Programming";
}
}
{
// private variable
private String name;
private void display()
{
System.out.println("The name is"+name);
}
}
public class Main
{
public static void main(String[] main)
{
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "Programming";
}
}
In the above example, we have declared a private variable named name and a private method named display(). When we run the program, we will get the following error:
Output:
I:\>javac Main.java
Main.java:17: error: name has private access in Data
I:\>javac Main.java
Main.java:17: error: name has private access in Data
d.name = "Programming";
^
^
The error is generated because we are trying to access the private variable and the private method of the Data class from the Main class.
You might be wondering what if we need to access those private variables. In this case, we can use the getters and setters method.
For example,
class Data
class Data
{
private String name;
// getter method
public String getName()
private String name;
// getter method
public String getName()
{
return this.name;
}
// setter method
public void setName(String name)
return this.name;
}
// setter method
public void setName(String name)
{
this.name= name;
}
}
public class Main
this.name= name;
}
}
public class Main
{
public static void main(String[] main)
public static void main(String[] main)
{
Data d = new Data();
// access the private variable using the getter and setter
d.setName("Programming");
System.out.println("The name is "+d.getName());
}
}
Output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac Main.java
ubuntu@ubuntu:~/Desktop/rkjava$ java Main
The name is Programming
Data d = new Data();
// access the private variable using the getter and setter
d.setName("Programming");
System.out.println("The name is "+d.getName());
}
}
Output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac Main.java
ubuntu@ubuntu:~/Desktop/rkjava$ java Main
The name is Programming
Protected Access Modifier
When methods and data members are declared protected, we can access them within the same package as well as from subclasses.
Ex:
class Animal
{
// protected method
protected void display()
{
System.out.println("It is Animal");
}
}
class Dog extends Animal
{
public static void main(String[] args)
{
// create an object of Dog class
Dog rkdog = new Dog();
// access protected method
rkdog.display();
}
}
Output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac Dog.java
ubuntu@ubuntu:~/Desktop/rkjava$ java Dog
It is Animal
ubuntu@ubuntu:~/Desktop/rkjava$ java Dog
It is Animal
Note:
In the above example, we have a protected method named display() inside the Animal class. The Animal class is inherited by the Dog class.
Public Access Modifier
When methods, variables, classes, and so on are declared public, then we can access them from anywhere. The public access modifier has no scope restriction.
For example,
// public class
class Animal
{
// public variable
public int legCount;
// public method
public void display()
class Animal
{
// public variable
public int legCount;
// public method
public void display()
{
System.out.println("It is an Animal");
System.out.println("It has " + legCount + " legs.");
}
}
System.out.println("It is an Animal");
System.out.println("It has " + legCount + " legs.");
}
}
// Main.java
public class Main
public class Main
{
public static void main( String[] args )
public static void main( String[] args )
{
// accessing the public class
Animal animal = new Animal();
// accessing the public variable
animal.legCount = 4;
// accessing the public method
animal.display();
}
}
Output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac Main.java
ubuntu@ubuntu:~/Desktop/rkjava$ java Main
It is an Animal
It has 4 legs.
// accessing the public class
Animal animal = new Animal();
// accessing the public variable
animal.legCount = 4;
// accessing the public method
animal.display();
}
}
Output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac Main.java
ubuntu@ubuntu:~/Desktop/rkjava$ java Main
It is an Animal
It has 4 legs.
Here,
The public class Animal is accessed from the Main class.
The public variable legCount is accessed from the Main class.
The public method display() is accessed from the Main class.
Note:
Access modifiers are mainly used for encapsulation, which can help us to control what part of a program can access the members of a class. So that misuse of data can be prevented.
No comments:
Post a Comment