java u 2p1
java u 2p1
java u 2p1
Class in Java
We know that java is an Object Oriented Programming Language. Whole java language functions
on the concept of classes and objects. Classes can be defined as a blueprint for making an object.
Let us understand what a class is through a real life example.
A car is a class. Swift DZire will be an object of the class car. It has attributes such as color, weight
etc. and methods such as brake, drive, etc. It can be defined as a medium that allows the user to
specify all attributes and methods that internally define the state and the behavior of the object.
To summarize we can say that : ‘A class is the basis of all computation in Java. ‘
Syntax
<access_modifier> class <ClassName>
{
//Class body containing objects, variables and methods
}
A basic example can be seen as-
public class Employee
{
String name, city, state;
int age, phn_num;
void display()
{
//body of the code;
}
}
UNIT -2 - Classes & Objects
To create a object of any class , we use the new keyword . This new keyword create the object at
runtime.
UNIT -2 - Classes & Objects
Syntax :
Classname objectName = newKeyword classname();
Example :
class Boxers {
public static void main(String [] args){
//creating new object of class type Boxers
Boxers var = new Boxers();
}
}
Summary Table
Modifier Same Class Same Package Subclass (Different Package) Other Classes
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ✘
(default) ✔ ✔ ✘ ✘
private ✔ ✘ ✘ ✘
Constructor in java
A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes. In Java,
a constructor is a block of codes similar to the method.
class A
{
// A Constructor
A( ){
// Parameterized constructor
Prep(int num, String name) {
this.num = num;
this.name = name;
System.out.println("Parameterized constructor called");
}
}
class Main {
public static void main(String[] args) {
// Calls the no-argument constructor
Prep prep1 = new Prep();
// Calls the parameterized constructor
Prep prep2 = new Prep(10, "Alice");
}
}
Output:
No-argument constructor called
Parameterized constructor called
Explanation:
1. No-argument constructor: This constructor sets default values for num and name.
2. Parameterized constructor: This constructor initializes num and name with the values
passed during object creation.
When we create prep1, the no-argument constructor is called. When we create prep2, the
parameterized constructor is called. Both constructors have different parameter lists, which is the
essence of constructor overloading.
Super and this Keyword
In Java, both the super and this keywords are used to refer to objects, but they serve different
purposes. Here's an easy differentiation with examples:
1. this Keyword:
• Refers to the current object (the object on which the method or constructor is called).
UNIT -2 - Classes & Objects
• Used to refer to instance variables or methods of the current object.
• It is also used to invoke another constructor within the same class (constructor chaining).
2. super Keyword:
• Refers to the parent (super) class of the current object.
• Used to access parent class methods and parent class constructors.
• Can be used to invoke a parent class constructor.
UNIT -2 - Classes & Objects
Example of super keyword:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Key Differences:
Used for constructor chaining (calling another Used to call the parent class
Constructor
constructor in the same class) constructor
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
UNIT -2 - Classes & Objects
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the classes
in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must be
in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class, it is
known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point. Some
UNIT -2 - Classes & Objects
pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.