java u 2p1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

UNIT -2 - Classes & Objects

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

Some features of class:


• A class can be imagined as a big data type, hence it’s functionality is as good as a data type.
• An outer class should be either public or default so that it can be accessed by the JVM.
o Public: public class
o Default: class
• A class can have:
o Methods
o Variables
o An object that can access these variables and methods.
• A class represents the common properties and actions of an object
• It has the following set of access modifiers that control the access or the visibility of a class:
o Public: restricts the access to the class itself. Only methods that are part of the same
class can access private members.
o Private: restricts the access to the class itself. Only methods that are part of the same
class can access private members.
o Protected: allows the class itself and all its subclasses to access the member.
Object in JAVA

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();
}
}

Assigning one object to another in java


In Java, when you assign one object to another, you're assigning a reference to the same memory
location, not creating a new independent copy of the object. Here's a breakdown:
Syntax :
ClassName obj1 = new ClassName();
ClassName obj2 = obj1; // obj2 now references the same object as obj1
In this case:
• obj1 and obj2 both point to the same object in memory.
• Modifications made through obj2 will affect the object that obj1 references and vice versa.
Example
class Example {
int value;
}
public class Main {
public static void main(String[] args) {
UNIT -2 - Classes & Objects
Example obj1 = new Example();
obj1.value = 10;
Example obj2 = obj1; // obj2 references the same object as obj1
System.out.println(obj1.value); // Outputs: 10
obj2.value = 20; // Modify obj2
System.out.println(obj1.value); // Outputs: 20 (obj1 sees the change)
}
}
Access control for class members in java
In Java, access control for class members (fields and methods) is defined using access modifiers.
These modifiers specify the visibility and accessibility of class members to other classes, subclasses,
and packages.
Access Modifiers
1. public:
o Accessible from anywhere in the program.
o No restrictions.
public class Example {
public int value; // Accessible from any class
}
2. protected:
o Accessible within the same package.
o Accessible in subclasses (even in different packages) through inheritance.
public class Example {
protected int value; // Accessible in same package and subclasses
}
3. (default) (no keyword):
o Accessible only within the same package.
o Also known as "package-private" access.
public class Example {
int value; // No modifier; package-private access
}
UNIT -2 - Classes & Objects
4. private:
o Accessible only within the same class.
o Not visible to subclasses or other classes, even in the same package.
public class Example {
private int value; // Accessible only within this class
}

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( ){

// We can create an object of the above class


// using the below statement. This statement
// calls above constructor.
A obj = new A ();
UNIT -2 - Classes & Objects
}
Types of Constructors in Java
Now is the correct time to discuss types of the constructor, so primarily there are two types of
constructors in java:
• No-argument constructor
• Parameterized Constructor
1. No-argument constructor
A constructor that has no parameter is known as the default constructor. If we don’t define a
constructor in a class, then the compiler creates a default constructor(with no arguments) for the
class. And if we write a constructor with arguments or no-arguments then the compiler does not
create a default constructor.
Example :
class Prep {
int num;
String name;
// Default constructor
Prep() {
System.out.println("Constructor called");
}
}
class Main {
public static void main(String[] args) {
Prep prep1 = new Prep(); // Calls the default constructor
}
}
Output :
Constructor called
Parameterized Constructor :
class Prep {
int num;
String name;
UNIT -2 - Classes & Objects
// Parameterized constructor
Prep(int num, String name) {
this.num = num;
this.name = name;
System.out.println("Constructor called with values: " + num + ", " + name);
}
}
class Main {
public static void main(String[] args) {
// Calling the parameterized constructor
Prep prep1 = new Prep(10, "John");
// Output will be generated from the constructor
}
}
Output :
Constructor called with values: 10, John.
Constructor overloading
Constructor overloading in Java occurs when a class has multiple constructors, each with different
parameter lists. This allows you to create objects in different ways, depending on the parameters
passed.
Here’s a simple example of constructor overloading:
class Prep {
int num;
String name;
// No-argument constructor
Prep() {
num = 0;
name = "Unknown";
System.out.println("No-argument constructor called");
}
UNIT -2 - Classes & Objects

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

Example of this keyword:


class Example {
int num;
// Constructor using 'this' to refer to the current object
Example(int num) {
this.num = num; // 'this.num' refers to the instance variable
}
void display() {
System.out.println("Value: " + this.num); // Using 'this' to access instance variable
}
public static void main(String[] args) {
Example obj = new Example(5);
obj.display();
}
}
Output:
Value: 5
• In the constructor, this.num refers to the instance variable num of the current object.
• The this keyword is also used in the display method to refer to the current object's num value.

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");
}
}

class Dog extends Animal {


void sound() {
super.sound(); // Calls the parent class method
System.out.println("Dog barks");
}

public static void main(String[] args) {


Dog dog = new Dog();
dog.sound();
}
}
Output:
Animal makes a sound
Dog barks
• super.sound() calls the sound() method from the parent class Animal.
• The super keyword can also be used to call the constructor of the parent class.

Key Differences:

Aspect this super

Refers To The current object The parent class (superclass)

Accessing current object's members (fields, Accessing parent class methods


Used For
methods) and constructors
UNIT -2 - Classes & Objects
Aspect this super

Used for constructor chaining (calling another Used to call the parent class
Constructor
constructor in the same class) constructor

super(); (invoke parent class


Example this.num = num; (access current object's field)
constructor)

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped together to perform
a certain task or operation. It is used to achieve the reusability of code. We write a method once and
use it many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.
The most important method in Java is the main() method. If you want to read more about the main()
method, go through the link java-main-method.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type,
name, and arguments. It has six components that are known as method header, as we have shown
in the following figure.

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.

public class Demo


{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9

You might also like