0% found this document useful (0 votes)
15 views21 pages

Java Classes, Objects, and Methods Guide

The document provides a comprehensive overview of Java programming concepts including classes, objects, methods, constructors, inheritance, method overloading, and access modifiers. It explains the syntax and usage of various features such as static members, method overriding, abstract classes, and arrays, along with examples for clarity. Additionally, it covers different types of inheritance and their implications in Java.

Uploaded by

yogeshpandiyan19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views21 pages

Java Classes, Objects, and Methods Guide

The document provides a comprehensive overview of Java programming concepts including classes, objects, methods, constructors, inheritance, method overloading, and access modifiers. It explains the syntax and usage of various features such as static members, method overriding, abstract classes, and arrays, along with examples for clarity. Additionally, it covers different types of inheritance and their implications in Java.

Uploaded by

yogeshpandiyan19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Notes – Class, Object, and Methods

Class
A class in Java is a blueprint or template from which individual objects are created. It defines the
structure and behavior of objects by encapsulating fields (variables) and methods (functions) into
a single unit.

In other words, a class acts as a user-defined data type that represents a real-world entity. A class
does not occupy memory by itself; memory is allocated only when an object of that class is created.
Syntax of a Class
class ClassName { Example of Class
// fields or data members // Defining a class 'Student' class Student
dataType variableName; { int rollNo; // data
member String name; //
data member
// methods
returnType methodName(parameters) { // method to display student details void
// method body display() {
} [Link]("Roll No: " + rollNo + ",
} Name: " + name);
}
}

Object
An object is an instance of a class. When a class is defined, no memory is allocated until objects
are created. Each object has its own copy of instance variables and can access the methods
defined in the class. Objects allow us to use the functionality defined in a class.
Syntax:
ClassName objectName = new ClassName();

Example:
public class Main {
public static void main(String[] args) {
// Creating an object of Student class
Student s1 = new Student();

// Assigning values to object variables


[Link] = 101;
[Link] = "Alice";

// Calling method using object


[Link]();
}}

Methods
A method in Java is a block of code that performs a specific task, similar to a function in other
programming languages. Methods allow code reusability, modularity, and better readability. A
method is always defined inside a class and can operate on the data members (fields) of that
class. There are two types of methods: predefined methods (like println()) and user-defined
methods.

Syntax:
returnType methodName(parameters) {
// method body
return value; // if returnType is not void
}

• returnType → Type of value the method returns (or void if it returns nothing).
• methodName → Name of the method.
• parameters → Values passed to the method (optional).

Example:
class Calculator {
// Method to add two numbers
int add(int a, int b) {
return a + b;
}

// Method without return type void


displayMessage() {
[Link]("Welcome to Calculator!");
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator(); // creating object

[Link](); // calling method without return


int sum = [Link](10, 20); // calling method with return
[Link]("Sum = " + sum);
} }

Constructor
A constructor in Java is a special type of method used to initialize objects. It has the same
name as the class and does not have a return type, not even void. A constructor is automatically
called when an object of a class is created, ensuring that the object starts in a valid state.
Constructors can be of two types: default constructor (provided by Java compiler if none is
defined) and parameterized constructor (defined by the programmer to accept arguments).

Syntax :
class ClassName {
// constructor
ClassName(parameters) {
// initialization code
}
}

Example:

class Student { int


rollNo;
String name;
// Constructor
Student(int r, String n) {
rollNo = r;
name = n;
}

void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}

public class Main {


public static void main(String[] args) { //
Creating objects using constructor
Student s1 = new Student(101, "Alice");
Student s2 = new Student(102, "Bob");

[Link]();
[Link]();
}
}

Output:
Roll No: 101, Name: Alice
Roll No: 102, Name: Bob

Method Overloading
Method Overloading in Java is a feature that allows a class to have multiple methods with the
same name but different parameter lists (different number or type of parameters). It increases code
readability and reusability. The compiler differentiates the methods based on their method
signature (method name + parameter list)

Syntax:
class ClassName { returnType
methodName(parameter list1) { ... } returnType methodName(parameter
list2) { ... }
}
Example:

class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers int


add(int a, int b, int c) {
return a + b + c;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]("Sum of 2 numbers are : " + [Link](5, 10));
[Link]("Sum of 3 numbers are : " + [Link](2, 4, 6));

}
}

Output:
Sum of 2 numbers are: 15
Sum of 3 numbers are: 12

Static Members
In Java, static members are class-level variables and methods that belong to the class rather than
any individual object. A static variable has only one copy shared across all objects of the class.
Static methods can be called without creating an object of the class, and they can directly access
only static data members.
Syntax of Static Members class
ClassName { static dataType
variableName;
static returnType methodName(parameters) { ... }
}
Example of Static Members
class Demo {
// Static variable (shared by all objects) static int
count = 0;

// Constructor Demo() { count++; //


increases whenever object is created
}

// Static method static void


showCount() {
[Link]("Number of objects created: " + count);
}
}

public class Main {


public static void main(String[] args) {
// Create objects
Demo d1 = new Demo();
Demo d2 = new Demo();
Demo d3 = new Demo();

// Call static method using class name


[Link]();
}
}

Nesting of Methods

Nesting of methods means calling one method inside another method of the same

class.
• In Java, a method cannot be defined inside another method, but a method can call
another method.
• This improves code reusability and modularity.
Syntax :

class Example {
void methodA() {
[Link]("Inside Method A");
methodB(); // calling another method inside this method
}

void methodB() {
[Link]("Inside Method B");
}
}

Example:
public class NestingExample {
void display() {
[Link]("This is display method.");
calculate(); // Calling another method inside this method
}

void calculate() {
int a = 5, b = 10;
int sum = a + b;
[Link]("Sum = " + sum);
}

public static void main(String[] args) {


NestingExample obj = new NestingExample();
[Link](); // This indirectly calls calculate() also
}
}

Inheritance (Extending the Class)


• Inheritance is the process by which one class (child class or subclass) can acquire the
properties and methods of another class (parent class or superclass).
• In Java, inheritance is achieved using the extends keyword.
• It promotes code reusability.

Syntax:
class Parent { //
fields and methods
}
class Child extends Parent { // inherits
fields and methods from Parent
}

Example:

class Animal {
void eat() {
[Link]("Animals can eat.");
}
}

class Dog extends Animal { // Dog inherits Animal


void bark() {
[Link]("Dog can bark.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited from Animal
[Link](); // Defined in Dog
}
}

Types of Inheritance in Java


Since Java does not support multiple inheritance through classes (to avoid ambiguity), the
main types are:

a. Single level Inheritance


b. Multilevel Inheritance
c. Multiple Inheritance (Java doesn’t Support)
d. Hierarchical Inheritance
e. Hybrid Inheritance
Parent class
a. Single level Inheritance

One class inherits another class.

Syntax: Child Class

class Parent {
//statements ;
}
class Child extends Parent{
//statements;
}

Example:

class Parent {
void showA() {
[Link]("Class A");
}
}

class Child extends Parent {


void showB() {
[Link]("Class B");
}
}

public class SingleLevelInheritance {


public static void main (String[] args){
Child obj = new Child();
[Link]();
[Link]();
}
}
Multilevel Inheritance

• A class inherits from another class, and other class inherits from another class.

Syntax :
class Parent {
//statements ; Parent Class
}
class Child1 extends Parent{
//statements;
}
class Child2 extends Child1{ Child1 Class
//statements;
}

Child2 Class
Example:

class Parent { void showA() {


[Link]("Class Parent ");
}
}

class Child1 extends Parent {


void showB() {
[Link]("Class Child1");
}
}
class Child2 extends Child1 {
void showC() {
[Link]("Class Child2");
}
}

public class MultiLevelInheritance {


public static void main (String[] args){
Child2 obj = new Child2();
[Link]();
[Link]();
[Link]();
}
}
Multiple Inheritance
It Contains multiple parent classes and single child class, Java doesn’t support directly this
inheritance to avoid confusion.

Parent 1 Parent 2

Child

Hierarchical Inheritance

It Contains multiple Childs classes inherit and single Parent class,

Syntax:

class Parent { Parent


// Statements
}
class child1 extends Parent {
// Statements
}
class child2 extends Parent { Child1 Child2
// Statements
}

Example:

class Parent{
void methodA{
[Link](“Method Parent”);
}
}
class Child1 extends Parent{
void methodB{
[Link](“Method child1”);
}}

class Child2 extends Parent{


void methodC{
[Link](“Method child2”);
}}

class Main {
public static void main (String[] args){
Child1 c1 = new Child1();
Child2 c2 = new Child2();
[Link](); //
[Link]();
[Link]();
[Link]();
}
}

Output:
Method parent
Method Child1
Method parent
Method Child2

Hybrid Inheritance
Combination of any two Inheritance

Note: write the same example as Multilevel Inheritance for this Inheritance.

Parent Class
Single
level
Inherita
nce C hild1 Class

Multilevel
Inheritanc
e Child2 Class
Overriding Methods

Definition:
Method overriding occurs when a subclass provides its own implementation of a method that is
already defined in its superclass. The overridden method in the subclass must have the same name,
return type, and parameters as the method in the superclass. Overriding is used to achieve
runtime polymorphism.

Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal obj = new Dog(); // runtime polymorphism
[Link]();
}
}

Output:
Dog Barks

Final Variables and Methods

• Final Variable: A variable declared with final cannot be changed after initialization.
• Final Method: A method declared with final cannot be overridden by subclasses.
• Final Class: A class declared as final cannot be inherited.
Example :

class Demo {
final int VALUE = 100; // final variable
final void display() { // final method
[Link]("Final method, cannot override");
}
}

Finalizer Method

The finalizer method in Java is called before an object is destroyed by the garbage collector. It is
defined using the finalize() method. However, its usage is discouraged in modern Java because
garbage collection is unpredictable.

Example:
class Demo {
protected void finalize() {
[Link]("Object is being destroyed");
}
}

public class Main {


public static void main(String[] args) {
Demo d = new Demo();
d = null;
[Link](); // requests garbage collection
}
}

Output:
Object is garbage collection

Abstract Methods and Classes

An abstract class in Java is a class that cannot be instantiated and may contain abstract methods
(methods without implementation). Abstract methods must be implemented by subclasses.
Abstract classes are declared using the abstract keyword.
Example
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


void draw() {
[Link]("Drawing a Circle");
}
}

public class Main {


public static void main(String[] args) {
Shape s = new Circle();
[Link]();
}
}

Output:
Drawing a Circle

Visibility Control (Access Modifiers)

Java provides access modifiers to control the visibility of classes, methods, and variables:

1. public – Accessible everywhere.


2. private – Accessible only within the class.
3. protected – Accessible within the same package and by subclasses.
4. default (no modifier) – Accessible only within the same package.

Example
class Demo {
public int a = 10;
private int b = 20;
protected int c = 30;
int d = 40; // default
}
Arrays

An array in Java is a data structure that allows you to store multiple values of the same type in a
single variable. Arrays are objects in Java and inherit from the [Link] class. They are
useful for managing collections of data efficiently.

Key Features of Arrays in Java

1. Fixed Size: Once an array is created, its size cannot be changed.


2. Homogeneous Data: All elements in an array must be of the same data type.
3. Indexed Access: Elements are accessed using their index, starting from 0.

Declaring and Initializing an Array


1. Declaration:

int[] numbers; // Preferred


// or
int numbers[]; // Valid but less common

2. Instantiation and Initialization:


numbers = new int[5]; // Creates an array of size 5

3. Combined Declaration and Initialization:


int[] numbers = {10, 20, 30, 40, 50}; // Direct initialization

Accessing Array Elements


You can access elements using their index:
Example:
int[] numbers = {10, 25, 30, 40, 50};
[Link](numbers[0]); // Accesses the first element
numbers[1] = 25; // Modifies the second element

Program:
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};

// Access and print array elements


for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + numbers[i]);
}
}
}

Multidimensional Array
A multidimensional array in Java is an array of arrays, where each element of the array is itself an
array. It is used to store data in a tabular form (like rows and columns in a table).

Syntax:
datatype[][] arrayName;
or
datatype[][][] arrayName; // 3D array
Accessing 2D Array Elements:
Accessing elements using row index and column index.

Syntax
arrayName[rowIndex][columnIndex];

Example:
public class Access2DArray {
public static void main(String[] args) {
int[][] matrix = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};

// Access and print a specific element


[Link]("Element at [0][1]: " + matrix[0][1]); // Output: 20
[Link]("Element at [2][2]: " + matrix[2][2]); // Output: 90

// Loop through all elements


[Link]("\nAll elements in the 2D array:");
for (int i = 0; i < [Link]; i++) { // rows
for (int j = 0; j < matrix[i].length; j++) { // columns
[Link](matrix[i][j] + " ");
}
[Link](); // new line after each row
}
}
}
String
A String in Java is a sequence of characters. It is an object of the class [Link] and is used
to store and manipulate text.

Syntax :
1. Using String Literals (Most Common):
String str = "Hello, World!";
2. Using the new Keyword:
String str = new String("Hello, Java!");
Note: This creates a new object in memory, even if the content is the same as another String.

Common String Methods / Functions:

Method Description

length() Returns the length of the string

charAt(index) Returns the character at a specific index

substring(start, end) Returns a substring

toLowerCase() Converts string to lowercase

toUpperCase() Converts string to uppercase

equals(str) Compares two strings (case-sensitive)

equalsIgnoreCase(str) Compares two strings (case-insensitive)

contains(str) Checks if substring exists

indexOf(char) Returns index of first occurrence

trim() Removes leading and trailing spaces

replace(old, new) Replaces characters or substrings


Example:

public class StringExample {


public static void main(String[] args) {
String name = "Java Programming";

[Link]("Original String: " + name);


[Link]("Length: " + [Link]());
[Link]("Character at index 5: " + [Link](5));
[Link]("Substring (5 to 16): " + [Link](5, 16));
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Contains 'gram': " + [Link]("gram"));
}
}

You might also like