JAVA OOP
What are Java Classes?
A class is a blueprint from which individual objects are created. In Java, everything
is related to classes and objects. Each class has its methods and attributes that can
be accessed and manipulated through the objects.
For example, if you want to create a class for students. In that case, "Student" will
be a class, and student records (like student1, student2, etc) will be objects.
Properties of Java Classes
A class does not take any byte of memory.
A class is just like a real-world entity, but it is not a real-world entity. It's a
blueprint where we specify the functionalities.
A class contains mainly two things: Methods and Data Members.
A class can also be a nested class.
Classes follow all of the rules of OOPs such as inheritance, encapsulation,
abstraction, etc.
Types of Class Variables
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks
are called local variables. The variable will be declared and initialized within
the method and the variable will be destroyed when the method has
completed.
Instance variables − Instance variables are variables within a class but
outside any method. These variables are initialized when the class is
Page 1 of 17
JAVA OOP
instantiated. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.
Class variables − Class variables are variables declared within a class,
outside any method, with the static keyword.
Syntax to create a Java class
Use the below syntax to create (declare) class in Java:
access_modifier class class_name{
data members;
constructors;
methods;
...;
}
What are Java Objects?
An object is a variable of the type class, it is a basic component of an object-
oriented programming system. A class has the methods and data members
(attributes), these methods and data members are accessed through an object.
Thus, an object is an instance of a class.
If we consider the real world, we can find many objects around us, cars, dogs,
humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, and color, and the behavior is
- barking, wagging the tail, and running.
Page 2 of 17
JAVA OOP
Creating (Declaring) a Java Object
As mentioned previously, a class provides the blueprints for objects. So basically,
an object is created from a class. In Java, the new keyword is used to create new
objects.
There are three steps when creating an object from a class −
Declaration − A variable declaration with a variable name with an object
type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.
Syntax to Create a Java Object
Consider the below syntax to create an object of the class in Java:
Class_name object_name = new Class_name([parameters]);
Note: parameters are optional and can be used while you're using constructors in
the class.
Rules for using the Classes and Objects Concepts
These rules are essential when declaring classes, import statements, and package
statements in a source file.
There can be only one public class per source file.
A source file can have multiple non-public classes.
Page 3 of 17
JAVA OOP
The public class name should be the name of the source file as well which
should be appended by .java at the end. For example − the class name
is public class Employee{} then the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should
be the first statement in the source file.
If import statements are present, then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the source
file.
Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.
Java Class Attributes
Java Class Attributes are variables that belong to a class. These are also called data
members or fields.
A class attribute defines the state or property of an object created from the class.
These attributes can be accessed and modified using methods inside the class.
They are declared inside the class but outside any method.
For example, there is a class "Student" with some data members (variables)
like roll_no, age, and name. These data members are considered class attributes.
Declaring Java Class Attributes
public class Dog {
String breed;
Page 4 of 17
JAVA OOP
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
In above class, we've fields like breed, age, and color which are also known as
class attributes.
Accessing Java Class Attributes
To access the class attribute, you need to create an object first and then use the
dot (.) operator with the object name. Class attributes can be also called within
the class methods directly.
Syntax
Use the below syntax to access a class attribute:
object_name.attribute_name;
class Dog {
// Declaring and initializing the attributes
Page 5 of 17
JAVA OOP
String breed = "German Shepherd";
int age = 2;
String color = "Black";
}
public class Main {
public static void main(String[] args) {
// Creating an object of the class Dog
Dog obj = new Dog();
// Accessing class attributes & printing the values System.out.println(obj.breed);
System.out.println(obj.age);
System.out.println(obj.color);
}
}
Modifying Java Class Attributes
To modify a class attribute, access the attribute and assign a new value using the
assignment (=) operator.
Syntax
Use the below syntax to modify a class attribute:
object_name.attribute_name = new_value;
Java Class Methods
Page 6 of 17
JAVA OOP
The class methods are methods that are declared within a class. They perform
specific operations and can access, modify the class attributes.
Creating (Declaring) Java Class Methods:
Declaring class methods is similar to declaring user-defined methods, but
class methods are written inside a class.
A method defines some behavior or action that the class (or its objects) can
perform.
Syntax of a Method:
java
Copy code
access_modifier return_type method_name(parameter_list) {
// method body
}
Example:
java
Copy code
public class Student {
void displayInfo() {
System.out.println("This is a student.");
}
}
Page 7 of 17
JAVA OOP
Example
Here is the source code of the above defined method called minimum(). This
method takes two parameters n1 and n2 and returns the minimum between the
two −
class Util {
/** the snippet returns the minimum between two numbers */
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Accessing Java Class Methods
To access a class method (public class method), you need to create an object first,
then by using the object you can access the class method (with the help of dot (.)
operator).
Syntax
Use the below syntax to access a Java public class method:
object_name.method_name([parameters]);
Page 8 of 17
JAVA OOP
Example
Following is the example to demonstrate how to define class method and how to
access it. Here, We've created an object of Util class and call
its minimum() method to get minimum value of given two numbers −
package com.tutorialspoint;
class Util {
public int minimum(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
public class Tester {
public static void main(String[] args) {
int a = 11;
int b = 6;
Page 9 of 17
JAVA OOP
Util util = new Util();
int c = util.minimum(a, b);
System.out.println("Minimum Value = " + c);
}
}
Output
Minimum value = 6
Public Vs. Static Class Methods
There are two types of class methods public and static class method. The public
class methods are accessed through the objects whereas, the static class
methods are accessed are accesses without an object. You can directly access the
static methods.
Example
The following example demonstrates the difference between public and static
class methods:
Open Compiler
public class Main {
// Creating a static method
static void fun1() {
System.out.println("fun1: This is a static method.");
}
Page 10 of 17
JAVA OOP
// Creating a public method
public void fun2() {
System.out.println("fun2: This is a public method.");
}
// The main() method
public static void main(String[] args) {
// Accessing static method through the class
fun1();
// Creating an object of the Main class
Main obj = new Main();
// Accessing public method through the object
obj.fun2();
}
}
Output
fun1: This is a static method.
fun2: This is a public method.
Page 11 of 17
JAVA OOP
What are Access Modifiers in Java? (gfg)
Access Modifiers in Java control the visibility or accessibility of classes, variables,
constructors, and methods in a program.
Types of Access Modifiers
There are 4 types of access modifiers available in Java:
1. Default - No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member, it is
said to have the default access modifier by default. This means only classes within
the same package can access it.
Example 1: Demonstrating Default Access Modifier Within
the Same Package
In this example, we will create two packages and the classes in
the packages will be having the default access modifiers and we
will try to access a class from one package from a class of the
second package.
// default access modifier
package p1;
// Class Geek is having
// Default access modifier
class Geek
{
void display()
{
System.out.println("Hello World!");
}
Page 12 of 17
JAVA OOP
Example 2: Error when Accessing Default Modifier Class
across Packages
In this example, the program will show the compile-time error
when we try to access a default modifier class from a different
package.
// error while using class from different
// package with default modifier
package p2;
import p1.*; // importing package p1
// This class is having
// default access modifier
class GeekNew {
public static void main(String args[]) {
// Accessing class Geek from package p1
Geek o = new Geek();
o.display();
}
}
Private Access Modifier in Java
The private keyword is used to declare a method or variable that is only
accessible within the same class.
It cannot be accessed outside the class, even if in the same package.
Top-level classes or interfaces cannot be declared as private because
private means it should be accessible only within an enclosing class, and
top-level classes are not enclosed by any other class.
Page 13 of 17
JAVA OOP
Example: In this example, we will create two classes A and B within the same
package p1. We will declare a method in class A as private and try to access this
method from class B and see the result.
/ Error while using class from different package with
// private access modifier
package p1;
// Class A
class A {
private void display() {
System.out.println("GeeksforGeeks");
}
}
// Class B
class B {
public static void main(String args[]) {
A obj = new A();
// Trying to access private method
// of another class
obj.display();
}
}
Explanation: The above code will show a compile-time error
when trying to access a private method from class B, even within
the same package.
Example of Invalid Private Top-Level Class:
private class MyClass { // ❌ Compile-time error
// ...
}
Valid Private Nested Class:
public class Outer {
private class Inner {
Page 14 of 17
JAVA OOP
// This is allowed
}
}
3. Protected Access Modifier
The protected access modifier is specified using the keyword protected. The
methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
Example 1: In this example, we will create two packages p1 and
p2. Class A in p1 is made public, to access it in p2. The method
display in class A is protected and class B is inherited from class
A and this protected method is then accessed by creating an
object of class B.
// protected access modifier
package p1;
// Class A
public class A {
protected void display() {
System.out.println("GeeksforGeeks");
}
}
So, it demonstrates that a protected method is accessible within
the same package.
Example 2: In this example, we will create two packages, p1
and p2. Class A in p1 has a protected method display. Class B in
p2 extends A and accesses the protected method
through inheritance by creating an object of class B.
// protected modifier
package p2;
// importing all classes
// in package p1
import p1.*;
// Class B is subclass of A
Page 15 of 17
JAVA OOP
class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.display();
}
}
Explanation: The above example demonstrates that a
protected method is accessible in a subclass from a different
package using inheritance.
4. Public Access Modifier
The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access
modifiers.
Classes, methods, or data members that are declared as public are
accessible from everywhere in the program. There is no restriction on the
scope of public data members.
Example 1: Here, the code shows that a public method is
accessible within the same package.
// public modifier
package p1;
public class A {
public void display() {
System.out.println("GeeksforGeeks");
}
}
Example 2: Here, the example shows that a public method is
accessible across packages.
// public access modifier
package p2;
import p1.*;
class B {
Page 16 of 17
JAVA OOP
public static void main(String args[]) {
A obj = new A();
obj.display();
}
}
Page 17 of 17