0% found this document useful (0 votes)
13 views

Class & Objects

The document provides an overview of classes and objects in Java, explaining how to create classes, instantiate objects, and define methods. It covers concepts such as method overloading, constructors, access modifiers, and the use of the 'this' keyword. Additionally, it discusses recursion and garbage collection, highlighting how Java manages memory and object lifecycle.

Uploaded by

Rishav Dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Class & Objects

The document provides an overview of classes and objects in Java, explaining how to create classes, instantiate objects, and define methods. It covers concepts such as method overloading, constructors, access modifiers, and the use of the 'this' keyword. Additionally, it discusses recursion and garbage collection, highlighting how Java manages memory and object lifecycle.

Uploaded by

Rishav Dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Class & Objects

• A Class is like an object constructor, or a "blueprint" for


creating objects.
Get your own Java Server
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;
int y = 10;

public static void main(String[] args) {


Main myObj1 = new Main();
Main myObj2 = new Main();
System.out.println(myObj1.x);
System.out.println(myObj2.y);
}
}
Using Multiple Classes

Main.java Second.java

public class Main { class Second {


int x = 5; public static void main(String[] args) {
} Main myObj = new Main();
System.out.println(myObj.x);
}
}
Methods
• A method is a block of code that performs a specific task.
• Suppose you need to create a program to create a circle and color it.
You can create two methods to solve this problem:
• a method to draw the circle
• a method to color the circle
• In Java, there are two types of methods:
• User-defined Methods: We can create our own method based on our
requirements.
• Standard Library Methods: These are built-in methods in Java that
are available to use.
User-defined methods:
• Declaring a Java Method
The syntax to declare a method is:
• returnType - It specifies what type of value a method returns For example if a
method has an int return type then it returns an integer value
If the method does not return a value, its return type is Void
• methodName - It is an identifier that is used to refer to the particular method in a
program.
• method body - It includes the programming statements that are used to perform
some tasks. The method body is enclosed inside the curly braces { }.
class Main {
// create a method
public int addNumbers(int a, int b)
{
int sum = a + b; // return value
return sum;
}
public static void main(String[] args) {
int num1 = 25;
int num2 = 15; // create an object of Main
Main obj = new Main(); // calling method
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}
Method Parameters in Java
• A method parameter is a value accepted by the method. As mentioned earlier, a
method can also have any number of parameters. For example,

• If a method is created with parameters, we need to pass the corresponding values


while calling the method. For example,
Example
class Main {
// method with no parameter
public void display1() {
System.out.println("Method without parameter");
}
// method with single parameter
public void display2(int a) {
System.out.println("Method with a single parameter: " + a);
}

public static void main(String[] args) {


// create an object of Main
Main obj = new Main();

// calling method with no parameter


obj.display1();

// calling method with the single parameter


obj.display2(24);
}
}
Example: An example to demonstrate the differences between static and public methods:
Access Methods With an Object
Example: Create a Car object named myCar. Call the fullThrottle() and speed() methods on the myCar object

// 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 The car is going as fast as it can!
Max speed is: 200
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
}
}
Standard Library Methods
• The standard library methods are built-in methods in Java that are readily available
for use.

• These standard libraries come along with the Java Class Library (JCL) in a Java archive
(*.jar) file with JVM and JRE.
• For example,
.
•print() is a method of java.io.PrintSteam
•The print("...") method prints the string inside quotation marks

•sqrt() is a method of Math class. It returns the square root of a number.


Example : Java Standard Library Method

public class Main {


public static void main(String[] args) {

// using the sqrt() method


System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}

Output:
Square root of 4 is: 2.0
.
Java Method Overloading
• In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both).
• These methods are called overloaded methods and this feature is called method overloading.
• For example:

• Here, the func() method is overloaded. These methods have the same name but accept different
arguments.
Private: These methods are only accessible within the class where they are defined and cannot be
2. Method Overloading by changing the data type of parameters
Java Constructors
• A constructor in Java is similar to a method that is invoked when an object of
the class is created.
• Unlike Java methods, a constructor has the same name as that of the class and
does not have any return type. For example,

• Here, Test() is a constructor. It has the same name as that of the class and doesn't
have a return type
Example: Java Constructor

class Main {
public String name; OUTPUT:
Constructor Called:
// constructor The name is Programiz
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}

public static void main(String[] args) {

// constructor is invoked while


// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}
Note:
• That the constructor name must match the class name, and it cannot have
a return type (like void).
• Also note that the constructor is called when the object is created.
• All classes have constructors by default:
• if you do not create a class constructor yourself, Java creates one for you.
However, then you are not able to set initial values for object attributes.
•A constructor cannot be abstract or static or final.
•A constructor can be overloaded but can not be overridden
Types of Constructor
• In Java, constructors can be divided into three types:
1.No-Arg Constructor
2.Parameterized Constructor
3.Default Constructor
• No-Arg Constructor - a constructor that does not accept any
arguments.
• Parameterized constructor - a constructor that accepts arguments.
• Default Constructor - a constructor that is automatically created by
the Java compiler if it is not explicitly defined.
1. Example: Java Private No-arg Constructor
class Main {

int i;

// constructor with no parameter


private Main() {
i = 5;
System.out.println("Constructor is called");
}

public static void main(String[] args) {

// calling the constructor without any parameter


Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Example: Java Public no-arg Constructors

class Company {
String name;

// public constructor
public Company() {
name = "Programiz";
}
}

class Main {
public static void main(String[] args) {

// object is created in another class


Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
2. Java Parameterized Constructor
Example: Parameterized Constructor
class Main {

String languages;
// constructor accepting single value

Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {

// call constructor by passing a single value


Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
3. Java Default Constructor
Example: Default Constructor

class Main {

int a;
boolean b;

public static void main(String[] args) {

// calls default constructor


Main obj = new Main();

System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Constructors Overloading in Java
• Similar to Java method overloading, we can also create two or more constructors with different
parameters. This is called constructor overloading.
public void getName() {
class Main { System.out.println("Programming Language: " + this.language);
String language; }

// constructor with no parameter public static void main(String[] args) {


Main() {
this.language = "Java"; // call constructor with no parameter
} Main obj1 = new Main();

// constructor with a single parameter // call constructor with a single parameter


Main(String language) { Main obj2 = new Main("Python");
this.language = language;
} obj1.getName();
obj2.getName();
}
}
Modifiers:
• In Java, access modifiers are used to set the accessibility (visibility)
of classes, interfaces, variables, methods, constructors, data members, and the setter
methods. For example,

• In the above example, we have declared 2 methods: method1() and method2(). Here,
•method1 is public - This means it can be accessed by other classes.
•method2 is private - This means it can not 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
declarations are visible only within the package
Default (package private)

Private declarations are visible within the class only

declarations are visible within the package or all


Protected subclasses
Public declarations are visible everywhere
• For classes, you can use either public or default:
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. For example,

package defaultPackage;
class Logger {
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.
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

// Animal.java file // Main.java


// public class public class Main {
public class Animal { public static void main( String[] args ) {
// public variable // accessing the public class
.public int legCount; Animal animal = new Animal();

// public method // accessing the public variable


public void display() { animal.legCount = 4;
System.out.println("I am an animal."); // accessing the public method
System.out.println("I have " + legCount + " legs."); animal.display();
} }
} }
• Private Access Modifier
• When variables and methods are declared private, they cannot be accessed outside
of the class.
• Protected Access Modifier
• When methods and data members are declared protected, we can access them
within the same package as well as from subclasses.
Importance:
• Access modifiers are mainly used for encapsulation.
• It 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.
this Keyword
• In Java, this keyword is used to refer to the current object inside
a method or a constructor. For example,
public class Main {
int x;
Value of x = 5
// Constructor with a parameter
public Main(int x) {
this.x = x;
}

// Call the constructor


public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
Usage
• The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name
• (because a class attribute is shadowed by a method or constructor
parameter).
• If you omit the keyword in the example above, the output would be "0" instead
of "5".
this can also be used to:
• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call
Recursion
• Recursion is the technique of making a function call itself. This technique provides a way
to break complicated problems down into simple problems which are easier to solve.
• Recursion may be a bit difficult to understand. The best way to figure out how it works is
to experiment with it.

• In this example, we have called


the recurse() method from inside
the main method (normal method call).
• And, inside the recurse() method, we are again
calling the same recurse method. This is a
recursive call.
• In order to stop the recursive call, we need to
provide some conditions inside the method.
Otherwise, the method will be called infinitely.
• Hence, we use the if...else statement (or similar
approach) to terminate the recursive call inside
the method.
Example Explained:

• When the sum() function is called, it adds


parameter k to the sum of all numbers smaller
than k and returns the result.
• When k becomes 0, the function just returns 0.
• When running, the program follows these steps:
Garbage Collection in Java
• Garbage collection in Java is the process by which Java programs perform
automatic memory management.
• Java programs compile to bytecode that can be run on a Java Virtual Machine, or
JVM for short.
• When Java programs run on the JVM, objects are created on the heap, which is a
portion of memory dedicated to the program.
• Eventually, some objects will no longer be needed.
• The garbage collector finds these unused objects and deletes them to free up
memory.
Ways to make an object eligible for Garbage Collector

• Even though the programmer is not responsible for destroying useless


objects but it is highly recommended to make an object
unreachable(thus eligible for GC) if it is no longer required.
• There are generally four ways to make an object eligible for garbage
collection.
• Nullifying the reference variable
• Re-assigning the reference variable
• An object created inside the method
• Island of Isolation

1.public static void gc(){}

You might also like