Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

The Concept of Java Classes and Objects

The document explains the fundamental concepts of Java classes and objects, detailing their definitions, properties, and types. It covers the structure of classes, including access modifiers, class variables, and methods, as well as the process of creating and manipulating objects. Additionally, it distinguishes between built-in and user-defined classes, and provides examples of class and object creation in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

The Concept of Java Classes and Objects

The document explains the fundamental concepts of Java classes and objects, detailing their definitions, properties, and types. It covers the structure of classes, including access modifiers, class variables, and methods, as well as the process of creating and manipulating objects. Additionally, it distinguishes between built-in and user-defined classes, and provides examples of class and object creation in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

The Concept of Java Classes and Objects

Classes and objects are the two most essential Java concepts that every
programmer must learn. Classes and objects are closely related and work together.
An object has behaviors and states, and is an instance of class. For instance, a cat
is an object—it’s color and size are states, and its meowing and clawing furniture are
behaviors. A class models the object, a blueprint or template that describes the state
or behavior supported by objects of that type.

What Is a Class?

We can define a class as a container that stores the data members and methods together.
These data members and methods are common to all the objects present in a particular
package.

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.

Every class we use in Java consists of the following components, as described below:

Access Modifier

Object-oriented programming languages like Java provide the programmers with four types
of access modifiers.

 Public

 Private

 Protected

 Default
These access modifiers specify the accessibility and users permissions of the methods and
members of the class.

Class Name

This describes the name given to the class that the programmer decides on, according to the
predefined naming conventions.

Body of the Class

The body of the class mainly includes executable statements. Apart from these, a class may
include keywords like "super" if you use a superclass, "implements" if you are inheriting
members, methods, and instances from the same class, and "interface" if you are inheriting
any members, methods, and instances from a different class.

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 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.

Type of Classes

In Java, we classify classes into two types:


Built-in Classes

Built-in classes are just the predefined classes that come along with the Java Development
Kit (JDK). We also call these built-in classes libraries. Some examples of built-in classes
include:

 java.lang.System

 java.util.Date

 java.util.ArrayList

 java.lang.Thread

User-Defined Classes

User-defined classes are rather self-explanatory. The name says it all. They are classes that
the user defines and manipulates in the real-time programming environment. User-defined
classes are broken down into three types:
Concrete Class

Concrete class is just another standard class that the user defines and stores the methods and
data members in.

Syntax:

class con{

//class body;

Abstract Class

Abstract classes are similar to concrete classes, except that you need to define them using the
"abstract" keyword. If you wish to instantiate an abstract class, then it should include an
abstract method in it. Otherwise, it can only be inherited.

Syntax:

abstract class AbstClas{

//method();

abstract void demo();

Interfaces

Interfaces are similar to classes. The difference is that while class describes an object’s
attitudes and behaviors, interfaces contain the behaviors a class implements. These interfaces
will only include the signatures of the method but not the actual method.

Syntax:

public interface demo{

public void signature1();


public void signature2();
}
public class demo2 implements demo{

public void signature1(){


//implementation;
}
public void signature2(){
//implementation;
}
}

Rules for Creating Classes

The following rules are mandatory when you're working with Java classes:

 The keyword "class" must be used to declare a class

 Every class name should start with an upper case character, and if you intend to
include multiple words in a class name, make sure you use the camel case

 A Java project can contain any number of default classes but should not hold
more than one public class

 You should not use special characters when naming classes

 You can implement multiple interfaces by writing their names in front of the class,
separated by commas

 You should expect a Java class to inherit only one parent class

Creating (Declaring) a Java Class


To create (declare) a class, you need to use access modifiers followed
by class keyword and class_name.

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;
...;
}
Java Classes/Objects
Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

Main.java
Create a class named "Main" with a variable x:

public class Main {

int x = 5;

Create an Object
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the object
name, and use the keyword new:

Example
Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {


Main myObj = new Main();

System.out.println(myObj.x);

Multiple Objects
You can create multiple objects of one class:

Example
Create two objects of Main:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

}
Using Multiple Classes
You can also create an object of a class and access it in another class. This is
often used for better organization of classes (one class has all the attributes
and methods, while the other class holds the main() method (code to be
executed)).

Remember that the name of the java file should match the class name. In
this example, we have created two files in the same directory/folder:

 Main.java
 Second.java

Main.java
public class Main {

int x = 5;

Second.java
class Second {

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

When both files have been compiled:

C:\Users\Your Name>javac Main.java


C:\Users\Your Name>javac Second.java

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

5
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.

If you compare the software object with a real-world object, they have
very similar characteristics. Software objects also have a state and a
behavior. A software object's state is stored in fields and behavior is
shown via methods. So, in software development, methods operate on
the internal state of an object, and the object-to-object communication is
done via methods.

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.
Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example (as
shown below). It is actually an attribute of the class. Or you could say that
class attributes are variables within a class:

ExampleGet your own Java Server


Create a class called "Main" with two attributes: x and y:

public class Main {

int x = 5;

int y = 3;

Another term for class attributes is fields.

Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):

The following example will create an object of the Main class, with the
name myObj. We use the x attribute on the object to print its value:

Example
Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

}
}

Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:

public class Main {

int x;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

Or override existing values:

Example
Change the value of x to 25:

public class Main {

int x = 10;

public static void main(String[] args) {


Main myObj = new Main();

myObj.x = 25; // x is now 25

System.out.println(myObj.x);

If you don't want the ability to override existing values, declare the attribute
as final:

Example
public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error: cannot assign a value to a


final variable

System.out.println(myObj.x);

Java Class Methods


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


Class methods declaration is similar to the user-defined
methods declaration except that class methods are declared within a
class.

The class methods are declared by specifying the access modifier followed by
the return type, method_name, and parameters list.
Syntax
Use the below syntax to declare a Java class method:

public class class_name {


modifier returnType nameOfMethod(Parameter List) {
// method body
}
}

The syntax shown above includes −

 modifier − It defines the access type of the method and it is optional


to use.
 returnType − The returns data type of the class method.
 nameOfMethod − This is the method name. The method signature
consists of the method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and
number of parameters of a method. These are optional, method
may contain zero parameters.
 method body − The method body defines what the method does with
the statements.

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]);

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

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 −

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;
Util util = new Util();

int c = util.minimum(a, b);


System.out.println("Minimum Value = " + c);
}
}

Output

Minimum value = 6

You learned from the Java Methods chapter that methods are declared within
a class, and that they are used to perform certain actions:

ExampleGet your own Java Server


Create a method named myMethod() in Main:

public class Main {

static void myMethod() {

System.out.println("Hello World!");

myMethod() prints a text (the action), when it is called. To call a method,


write the method's name followed by two parentheses () and a semicolon;

Example
Inside main, call myMethod():

public class Main {

static void myMethod() {

System.out.println("Hello World!");

}
public static void main(String[] args) {

myMethod();

// Outputs "Hello World!"

Static vs. Public


You will often see Java programs that have either static or public attributes
and methods.

In the example above, we created a static method, which means that it can
be accessed without creating an object of the class, unlike public, which can
only be accessed by objects:

Example
An example to demonstrate the differences
between static and public methods:

public class Main {

// Static method

static void myStaticMethod() {

System.out.println("Static methods can be called without creating


objects");

// Public method

public void myPublicMethod() {

System.out.println("Public methods must be called by creating


objects");
}

// Main method

public static void main(String[] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main

myObj.myPublicMethod(); // Call the public method on the object

Note: You will learn more about these keywords (called modifiers) in
the Java Modifiers chapter.

Access Methods With an Object


Example
Create a Car object named myCar. Call
the fullThrottle() and speed() methods on the myCar object, and run the
program:

// Create a Main class

public class Main {

// Create a fullThrottle() method

public void fullThrottle() {


System.out.println("The car is going as fast as it can!");

// Create a speed() method and add a parameter

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);

// Inside main, call the methods on the myCar object

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

// The car is going as fast as it can!

// Max speed is: 200

Example explained
1) We created a custom Main class with the class keyword.

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some
text, when they are called.

4) The speed() method accepts an int parameter called maxSpeed - we will


use this in 8).

5) In order to use the Main class and its methods, we need to create
an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar.

8) Then, we call the fullThrottle() and speed() methods on


the myCar object, and run the program using the name of the object (myCar),
followed by a dot (.), followed by the name of the method
(fullThrottle(); and speed(200);). Notice that we add an int parameter
of 200 inside the speed() method.

Remember that..
The dot (.) is used to access the object's attributes and methods.

To call a method in Java, write the method name followed by a set of


parentheses (), followed by a semicolon (;).

A class must have a matching filename (Main and Main.java).

Using Multiple Classes


Like we specified in the Classes chapter, it is a good practice to create an
object of a class and access it in another class.

Remember that the name of the java file should match the class name. In
this example, we have created two files in the same directory:

 Main.java
 Second.java

Main.java
public class Main {

public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);


}

Second.java
class Second {

public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

When both files have been compiled:

C:\Users\Your Name>javac Main.java


C:\Users\Your Name>javac Second.java

Run the Second.java file:

C:\Users\Your Name>java Second

And the output will be:

The car is going as fast as it can!


Max speed is: 200

public class Puppy {


int puppyAge;

public Puppy(String name) {


// This constructor has one parameter, <i>name</i>.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

public int getAge( ) {


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}

Output
If we compile and run the above program, then it will produce the
following result −

Name chosen is :tommy


Puppy's age is :2
Variable Value :2

Example 2
Following is the EmployeeTest class, which creates two instances of the
class Employee and invokes the methods for each object to assign values
for each variable.
Save the following code in EmployeeTest.java file.

import java.io.*;
public class EmployeeTest {

public static void main(String args[]) {


/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");

// Invoking methods for each object created


empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();

empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}

Output
Now, compile both the classes and then run EmployeeTest to see the
result as follows −

C:\> javac Employee.java


C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0

Key Differences Between Java Classes and Objects

The key differences between a class and an object are:

Class:

 A class is a blueprint for creating objects

 A class is a logical entity

 The keyword used is "class"

 A class is designed or declared only once

 The computer does not allocate memory when you declare a class

Objects:

 An object is a copy of a class

 An object is a physical entity

 The keyword used is "new"

 You can create any number of objects using one single class

 The computer allocates memory when you declare a class

Java Class Attributes


Java class attributes are the variables that are bound in a class i.e., the
variables which are used to define a class are class attributes.

A class attribute defines the state of the class during program execution.
A class attribute is accessible within class methods by default.
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.

Creating (Declaring) Java Class Attributes


To create (declare) a class attribute, use the access modifier followed by
the data type and attribute name. It's similar to declaring a variable.

Syntax
Use the below syntax to declare a class attribute:

access_modifier type attribute_name;

Example: Declaring Java Class Attributes

public class Dog {


String breed;
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;

Example: Accessing Java Class Attributes


Consider this example, demonstrating how to access the class attributes.

class Dog {
// Declaring and initializing the attributes
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);
}
}

Output

German Shepherd
2
Black

this Keyword in Java Class Methods


this is a keyword in Java which is used as a reference to the object of the current class, with
in an instance method or a constructor. Using this you can refer the members of a class such
as constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors

In general, the keyword this is used to −

 Differentiate the instance variables from local variables if they have same names,
within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
 Call one type of constructor (parametrized constructor or default) from other in a
class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}

Student(int age) {
this.age = age;
}
}

Example: Using this Keyword in Java Class Methods


Here is an example that uses this keyword to access the members of a class. Copy and paste
the following program in a file with the name, Tester.java.

public class Tester {


// Instance variable num
int num = 10;

Tester() {
System.out.println("This is an example program on keyword this");
}

Tester(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the instance variable num
this.num = num;
}

public void greet() {


System.out.println("Hi Welcome to Tutorialspoint");
}

public void print() {


// Local variable num
int num = 20;

// Printing the local variable


System.out.println("value of local variable num is : "+num);

// Printing the instance variable


System.out.println("value of instance variable num is : "+this.num);

// Invoking the greet method of a class


this.greet();
}

public static void main(String[] args) {


// Instantiating the class
Tester obj1 = new Tester();

// Invoking the print method


obj1.print();

// Passing a new value to the num variable through parametrized constructor


Tester obj2 = new Tester(30);

// Invoking the print method again


obj2.print();
}
}

Output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

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:

public class Main {


// Creating a static method
static void fun1() {
System.out.println("fun1: This is a static method.");
}

// 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.

The finalize( ) Method


It is possible to define a method that will be called just before an object's
final destruction by the garbage collector. This method is called finalize( ),
and it can be used to ensure that an object terminates cleanly.

For example, you might use finalize( ) to make sure that an open file
owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The
Java runtime calls that method whenever it is about to recycle an object
of that class.

Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.

The finalize( ) method has this general form −

protected void finalize( ) {


// finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize(


) by code defined outside its class.

This means that you cannot know when or even if finalize( ) will be
executed. For example, if your program ends before garbage collection
occurs, finalize( ) will not execute.

Java Constructors
Java constructors are special types of methods that are used to initialize
an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit
return type.
Typically, you will use a constructor to give initial values to the
instance variables defined by the class or to perform any other start-up
procedures required to create a fully formed object.

All classes have constructors, whether you define one or not because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your constructor, the default
constructor is no longer used.

Rules for Creating Java Constructors


You must follow the below-given rules while creating Java constructors:

 The name of the constructors must be the same as the class name.
 Java constructors do not have a return type. Even do not use void
as a return type.
 There can be multiple constructors in the same class, this concept is
known as constructor overloading.
 The access modifiers can be used with the constructors, use if you
want to change the visibility/accessibility of constructors.
 Java provides a default constructor that is invoked during the time
of object creation. If you create any type of constructor, the default
constructor (provided by Java) is not invoked.

Creating a Java Constructor


To create a constructor in Java, simply write the constructor's name (that
is the same as the class name) followed by the brackets and then write
the constructor's body inside the curly braces ({}).

Syntax
Following is the syntax of a constructor −

class ClassName {
ClassName() {
}
}

Example to create a Java Constructor


The following example creates a simple constructor that will print "Hello
world".

public class Main {


// Creating a constructor
Main() {
System.out.println("Hello, World!");
}

public static void main(String[] args) {


System.out.println("The main() method.");

// Creating a class's object


// that will invoke the constructor
Main obj_x = new Main();
}
}

This program will print:

The main() method.


Hello, World!

Types of Java Constructors


There are three different types of constructors in Java, we have listed
them as follows:

 Default Constructor
 No-Args Constructor
 Parameterized Constructor
1. Default Constructor
If you do not create any constructor in the class, Java provides a default
constructor that initializes the object.

Example: Default Constructor (A Class Without Any


Constructor)
In this example, there is no constructor defined by us. The default
constructor is there to initialize the object.

public class Main {


int num1;
int num2;

public static void main(String[] args) {


// We didn't created any structure
// a default constructor will invoke here
Main obj_x = new Main();

// Printing the values


System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}

Output

num1 : 0
num2 : 0

2. No-Args (No Argument) Constructor


As the name specifies, the No-argument constructor does not accept any
argument. By using the No-Args constructor you can initialize the class
data members and perform various activities that you want on object
creation.

Example: No-Args Constructor


This example creates no-args constructor.

public class Main {


int num1;
int num2;

// Creating no-args constructor


Main() {
num1 = -1;
num2 = -1;
}

public static void main(String[] args) {


// no-args constructor will invoke
Main obj_x = new Main();

// Printing the values


System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}

Output

num1 : -1
num2 : -1

3. Parameterized Constructor
A constructor with one or more arguments is called a parameterized
constructor.

Most often, you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same way that
they are added to a method, just declare them inside the parentheses
after the constructor's name.

Example 1: Parameterized Constructor


This example creates a parameterized constructor.

public class Main {


int num1;
int num2;
// Creating parameterized constructor
Main(int a, int b) {
num1 = a;
num2 = b;
}

public static void main(String[] args) {


// Creating two objects by passing the values
// to initialize the attributes.
// parameterized constructor will invoke
Main obj_x = new Main(10, 20);
Main obj_y = new Main(100, 200);

// Printing the objects values


System.out.println("obj_x");
System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);

System.out.println("obj_y");
System.out.println("num1 : " + obj_y.num1);
System.out.println("num2 : " + obj_y.num2);
}
}

Output

obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200

Example 2: Parameterized Constructor


Here is a simple example that uses a constructor −

// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}

You would call constructor to initialize objects as follows −

public class ConsDemo {


public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

Output

10 20

Constructor Overloading in Java


Constructor overloading means multiple constructors in a class. When you
have multiple constructors with different parameters listed, then it will be
known as constructor overloading.

Example: Constructor Overloading


In this example, we have more than one constructor.

// Example of Java Constructor Overloading


// Creating a Student Class
class Student {
String name;
int age;

// no-args constructor
Student() {
this.name = "Unknown";
this.age = 0;
}

// parameterized constructor having one parameter


Student(String name) {
this.name = name;
this.age = 0;
}

// parameterized constructor having both parameters


Student(String name, int age) {
this.name = name;
this.age = age;
}

public void printDetails() {


System.out.println("Name : " + this.name);
System.out.println("Age : " + this.age);
}
}

public class Main {


public static void main(String[] args) {
Student std1 = new Student(); // invokes no-args constructor
Student std2 = new Student("Jordan"); // invokes parameterized constructor
Student std3 = new Student("Paxton", 25); // invokes parameterized constructor

// Printing details
System.out.println("std1...");
std1.printDetails();

System.out.println("std2...");
std2.printDetails();

System.out.println("std3...");
std3.printDetails();
}
}
Output

td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25

Java access modifiers are used to specify the scope of the variables, data
members, methods, classes, or constructors. These help to restrict and
secure the access (or, level of access) of the data.

There are four different types of access modifiers in Java, we have listed
them as follows:

 Default (No keyword required)


 Private
 Protected
 Public

Default Access Modifier


Default access modifier means we do not explicitly declare an access
modifier for a class, field, method, etc.

A variable or method declared without any access control modifier is


available to any other class in the same package. The fields in an
interface are implicitly public static final and the methods in an interface
are by default public.
Example of Default Access Modifiers
Variables and methods can be declared without any modifiers, as in the
following examples −

String version = "1.5.1";

boolean processOrder() {
return true;
}

Private Access Modifier


Methods, variables, and constructors that are declared private can only be
accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if
public getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates
itself and hides data from the outside world.

Examples of Private Access Modifiers

Example 1
The following class uses private access control −

public class Logger {


private String format;

public String getFormat() {


return this.format;
}

public void setFormat(String format) {


this.format = format;
}
}
Here, the format variable of the Logger class is private, so there's no way
for other classes to retrieve or set its value directly.

So, to make this variable available to the outside world, we defined two
public methods: getFormat(), which returns the value of format,
and setFormat(String), which sets its value.

Example 2
In this example, the data members and class methods of the Logger class
are private. We are trying to access those class methods in another
class Main.

class Logger {
private String format;

private String getFormat() {


return this.format;
}

private void setFormat(String format) {


this.format = format;
}
}

public class Main {


public static void main(String[] args) {
// Creating an object
Logger log = new Logger();
// Setting the value
log.setFormat("Text");
// Getting the value
System.out.println(log.getFormat());

}
}

Output

Main.java:18: error: setFormat(String) has private access in Logger


log.setFormat("Text");
^
Main.java:20: error: getFormat() has private access in Logger
System.out.println(log.getFormat());
^
2 errors

Protected Access Modifier


Variables, methods, and constructors, which are declared protected in a
superclass can be accessed only by the subclasses in other package or
any class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces.


Methods, fields can be declared protected, however methods and fields in
a interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.

Examples of Protected Access Modifiers

Example 1
The following parent class uses protected access control, to allow its child
class override openSpeaker() method −

class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}

class StreamingAudioPlayer extends AudioPlayer {


boolean openSpeaker(Speaker sp) {
// implementation details
}
}

Here, if we define openSpeaker() method as private, then it would not be


accessible from any other class other than AudioPlayer. If we define it as
public, then it would become accessible to all the outside world. But our
intention is to expose this method to its subclass only, that's why we have
used protected modifier.

Example 1
This example demonstrates the use of protected access modifier.

// Class One
class One {
protected void printOne() {
System.out.println("printOne method of One class.");
}
}

// Inheriting class One on Main


public class Main extends One {
public static void main(String[] args) {
// Creating an object of Main class
Main obj = new Main();

// Calling printOne() method of class One


// through the object of Main class
obj.printOne();
}
}

Output

printOne method of One class.

Public Access Modifier


A class, method, constructor, interface, etc. declared public can be
accessed from any other class. Therefore, fields, methods, blocks
declared inside a public class can be accessed from any class belonging to
the Java Universe.

However, if the public class we are trying to access is in a different


package, then the public class still needs to be imported. Because of class
inheritance, all public methods and variables of a class are inherited by its
subclasses.

Syntax
The following function uses public access control −

public static void main(String[] arguments) {


// ...
}

The main() method of an application has to be public. Otherwise, it could


not be called by a Java interpreter (such as java) to run the class.

Example of Public Access Modifiers


This example demonstrates the use of public access modifier.

// Class One
class One {
public void printOne() {
System.out.println("printOne method of One class.");
}
}

public class Main {


public static void main(String[] args) {
// Creating an object of class One
One obj = new One();

// Calling printOne() method of class One


obj.printOne();
}
}

Output

This example demonstrates the use of public access modifier.

Access Modifiers and Inheritance


The following rules for inherited methods are enforced −
 Methods declared public in a superclass also must be public in all
subclasses.
 Methods declared protected in a superclass must either be protected
or public in subclasses; they cannot be private.
 Methods declared private are not inherited at all, so there is no rule
for them.

The following table shows the summary of the accessibility in the


same/different classes (or, packages) based on the access modifiers.

Example of Access Modifiers with Inheritance


In this example, we've created a class with a private variable age and a
variable with default scope as name. Using setter/getter method, we're
updating age and getting value and name is updated directly.

public class Puppy {


private int age;
String name;

public Puppy() {
}

public void setAge( int age ) {


this.age = age;
}

public int getAge( ) {


return age;
}

public static void main(String []args) {


Puppy myPuppy = new Puppy();

// update age variable using method call


myPuppy.setAge( 2 );

// update name directly


myPuppy.name = "Tommy";
System.out.println("Age: " + myPuppy.getAge() +", name: " + myPuppy.name );
}
}

Output

Age: 2, name: Tommy

Java access modifiers are used to specify the scope of the variables, data members, methods,
classes, or constructors. These help to restrict and secure the access (or, level of access) of the
data.

There are four different types of access modifiers in Java, we have listed them as follows:

 Default (No keyword required)


 Private
 Protected
 Public

Default Access Modifier


Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc.

A variable or method declared without any access control modifier is available to any other
class in the same package. The fields in an interface are implicitly public static final and the
methods in an interface are by default public.

Example of Default Access Modifiers


Variables and methods can be declared without any modifiers, as in the following examples −
String version = "1.5.1";

boolean processOrder() {
return true;
}

Private Access Modifier


Methods, variables, and constructors that are declared private can only be accessed within the
declared class itself.

Private access modifier is the most restrictive access level. Class and interfaces cannot be
private.

Variables that are declared private can be accessed outside the class, if public getter methods
are present in the class.

Using the private modifier is the main way that an object encapsulates itself and hides data
from the outside world.

Examples of Private Access Modifiers

Example 1
The following class uses private access control −

public class Logger {


private String format;

public String getFormat() {


return this.format;
}

public void setFormat(String format) {


this.format = format;
}
}

Here, the format variable of the Logger class is private, so there's no way for other classes to
retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String), which sets
its value.

Example 2
In this example, the data members and class methods of the Logger class are private. We are
trying to access those class methods in another class Main.

class Logger {
private String format;

private String getFormat() {


return this.format;
}

private void setFormat(String format) {


this.format = format;
}
}

public class Main {


public static void main(String[] args) {
// Creating an object
Logger log = new Logger();
// Setting the value
log.setFormat("Text");
// Getting the value
System.out.println(log.getFormat());

}
}

Output

Main.java:18: error: setFormat(String) has private access in Logger


log.setFormat("Text");
^
Main.java:20: error: getFormat() has private access in Logger
System.out.println(log.getFormat());
^
2 errors

Protected Access Modifier


Variables, methods, and constructors, which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the
protected members' class.

The protected access modifier cannot be applied to class and interfaces. Methods, fields can
be declared protected, however methods and fields in a interface cannot be declared
protected.

Protected access gives the subclass a chance to use the helper method or variable, while
preventing a nonrelated class from trying to use it.

Examples of Protected Access Modifiers

Example 1
The following parent class uses protected access control, to allow its child class
override openSpeaker() method −

class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}

class StreamingAudioPlayer extends AudioPlayer {


boolean openSpeaker(Speaker sp) {
// implementation details
}
}

Here, if we define openSpeaker() method as private, then it would not be accessible from any

other class other than AudioPlayer. If we define it as public, then it would become accessible
to all the outside world. But our intention is to expose this method to its subclass only, that's
why we have used protected modifier.

Example 1
This example demonstrates the use of protected access modifier.
// Class One
class One {
protected void printOne() {
System.out.println("printOne method of One class.");
}
}

// Inheriting class One on Main


public class Main extends One {
public static void main(String[] args) {
// Creating an object of Main class
Main obj = new Main();

// Calling printOne() method of class One


// through the object of Main class
obj.printOne();
}
}

Output

printOne method of One class.

Public Access Modifier


A class, method, constructor, interface, etc. declared public can be accessed from any other
class. Therefore, fields, methods, blocks declared inside a public class can be accessed from
any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package, then the public
class still needs to be imported. Because of class inheritance, all public methods and variables
of a class are inherited by its subclasses.

Syntax
The following function uses public access control −

public static void main(String[] arguments) {


// ...
}
The main() method of an application has to be public. Otherwise, it could not be called by a
Java interpreter (such as java) to run the class.

Example of Public Access Modifiers


This example demonstrates the use of public access modifier.

// Class One
class One {
public void printOne() {
System.out.println("printOne method of One class.");
}
}

public class Main {


public static void main(String[] args) {
// Creating an object of class One
One obj = new One();

// Calling printOne() method of class One


obj.printOne();
}
}

Output

This example demonstrates the use of public access modifier.

Access Modifiers and Inheritance


The following rules for inherited methods are enforced −

 Methods declared public in a superclass also must be public in all subclasses.


 Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
 Methods declared private are not inherited at all, so there is no rule for them.

The following table shows the summary of the accessibility in the same/different classes (or,
packages) based on the access modifiers.
Example of Access Modifiers with Inheritance
In this example, we've created a class with a private variable age and a variable with default
scope as name. Using setter/getter method, we're updating age and getting value and name is
updated directly.

public class Puppy {


private int age;
String name;

public Puppy() {
}

public void setAge( int age ) {


this.age = age;
}

public int getAge( ) {


return age;
}

public static void main(String []args) {


Puppy myPuppy = new Puppy();

// update age variable using method call


myPuppy.setAge( 2 );

// update name directly


myPuppy.name = "Tommy";
System.out.println("Age: " + myPuppy.getAge() +", name: " + myPuppy.name );
}
}

Output
Age: 2, name: Tommy
Print Page

You might also like