[go: up one dir, main page]

0% found this document useful (0 votes)
7 views32 pages

Unit II Class Object and Methods

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)
7 views32 pages

Unit II Class Object and Methods

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
You are on page 1/ 32

Unit II Classes, Objects and Methods

Class
It is a template/Blueprint from which objects are created.
There are two types of class
Pre-defined class
Some of the predefined classes in java are
 Object Class: Object class is the root of Java class hierarchy.
 Math Class
 String Class
 System Class
 Scanner Class

User defined class


A class which is created by java programmer is called user defined class.
Some of the user-defined classes are used in java i.e., car, furniture, student.

Example
Class classname
{
------------------------ // data or fields or variables
// methods
}

Variable:

A variable is a container which holds the value while the Java program is
executed.

Syntax:

Datatype variableName = value;

Example:

int age = 25; // Assigning a value to the variable

Variable is a name of memory location.There are three types of variables in


Java:

1
o local variable

o instance variable
o static variable

• Objects:
The Object is the real-time entity having some state and behaviour. In Java, Object is
an instance of the class having the instance variables like the state of the object and the
methods as the behaviour of the object. The object of a class can be created by using
the new keyword in Java Programming language.
Key points about object
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behaviour.
The object is an instance of a class.
Example
Car is a object which has state (name, color, model, number) and behaviour (speed,
etc).

2
Creating the Object
Using the new keyword is the most popular way to create an object or instance of the
class. When we create an instance of the class by using the new keyword, it allocates
memory for the newly created object and also returns the reference of that object to
that memory.
The syntax for creating an object is:

ClassName objectname= new ClassName();

Example: Student S1 = new Student();

Methods and objects


Methods are declared inside the body of the class immediately after the
declaration of instance variables.
Members of a class are accessible by objects depending upon their accessibility
conditions. If the members are private they cannot be accessed outside the class.To
access class members we must use the concerned “object” and the “dot”operator.

The general syntax is

objectname.variablename = value;
objectname.methodname(parameter-list);

Example:
s1.stdname=10;
 Here “s1” is the “object name” ,variable name is “stdname”.
s1.display( );
 “s1” object name and “display” is the method name.

Constructor
Every class has a constructor. If the constructor is not defined in the class, the Java
compiler builds a default constructor for that class. While a new object is created,
at least one constructor will be invoked. The main rule of constructors is that they

3
should have the same name as the class. A class can have more than one constructor.
Constructors are used for initializing new objects.

Rules for writing Constructor


a) Constructor(s) of a class must have same name as the class name in which
it resides.
b) A constructor in Java cannot be abstract, final, static and synchronized.
c) Constructor does not contain return type.

Following is an example of a constructor Example:


public class student
{
public student()
{
// Constructor
}
public student(String name)
{
// This constructor has one parameter, name.
}
}

Types of Constructors
Default Constructor in Java
A constructor that has no parameters is known as default constructor. A default constructor is
invisible. And if we write a constructor with no arguments, the compiler does not create a default
constructor. Once you define a constructor (with or without parameters), the compiler no longer
provides the default constructor

Parameterized Constructor:
A constructor that has parameters is known as parameterized constructor.
// Java Program to illustrate calling of parameterized constructor.

class Student
{
String s;
int age;
Student(String str, int a)
{
s=str;

4
age=a;
System.out.println("name="+s);
System.out.println("age="+age);
}

public static void main(String args[])


{
Student ob=new Student("Aliya",21);
}
}

Copy Constructor
A copy constructor is a special constructor that creates a new object by copying values from an
existing object of the same class. It copies the values of all member variables, including primitive
types, arrays, and object references. It is specially used for creating deep copies of an object, which
ensures any modification made to the copied object will not reflect the original object.
Example:
class A2
{
String name;
int age;
A2(String stuname,int stuage)
{
name=stuname;
age=stuage;
}
A2(A2 ob)
{
name=ob.name;
age=ob.age;
}
void show()
{
System.out.println(name+age);
}

public static void main(String args[])


{
A2 ob1=new A2("sam",21);
A2 ob2=new A2(ob1);
ob1.show();
ob2.show();

}
}

Static Member Data and Static Member Methods in Java

In Java, the keyword static is used to create class-level members — meaning the member belongs to
the class rather than to any specific object.

5
Static Member Data (Static Variables)

Shared by all objects of the class.

Stored in memory only once.

Can be accessed using the class name (e.g., ClassName.variableName).

Static Member Methods:

Can access only static data (not instance variables directly).

Can be called without creating an object.

Example 1:

class Calculator {

static int add(int a, int b) {

return a + b;

public static void main(String[] args) {

int result = add(10, 20);

System.out.println("Sum = " + result);

Example 2:

class Calculator {

// Static method

static int add(int a, int b) {

return a + b;

6
public class Main {

public static void main(String[] args) {

// Calling static method without creating an object

int result = Calculator.add(10, 20);

System.out.println("Sum = " + result);

Nesting of Methods:

In Java, nesting of methods means calling one method from another method within the same
class.

class Example {

void greet() {

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

void welcome() {

System.out.println("Welcome to Java!");

greet(); }

public static void main(String[] args) {

Example obj = new Example();

obj.welcome();

Recursion:

Recursion is a technique in which a method calls itself to solve a problem

class RecursionExample {

7
int factorial(int n) {

if (n == 0 || n == 1)

return 1;

else

return n * factorial(n - 1); // recursive call

public static void main(String[] args) {

RecursionExample obj = new RecursionExample();

int result = obj.factorial(5);

System.out.println("Factorial of 5 is: " + result);

Nested Classes:

Nested classes are divided into two categories:

static nested class: Nested classes that are declared static are called static nested classes.

inner class: An inner class is a non-static nested class.

1. Static Nested Class

A class defined with static inside another class is called static

It can access only static members of the outer class.

class Outer {

static int a = 10;

static class inner {

void display() {

System.out.println("Static nested class, a = " + a);

8
}

public static void main(String[] args) {

Outer.inner obj = new Outer.inner(); // No need to create Outer object

obj.display();

Non-static (Inner) Class //Member Class

A class defined inside another class without static, and it can access all members of the outer class.

class Outer {

int x = 5;

class Inner {

void show() {

System.out.println("Non-static inner class, x = " + x);

public static void main(String[] args) {

Outer outerObj = new Outer();

Outer.Inner innerObj = outerObj.new Inner(); // Requires Outer object

innerObj.show();

9
}

Local Inner Class –

· Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a
method body.

· It is local to the scope of that method or block, just like local variables.

It cannot be accessed outside the method where it is defined.

Example

class Outer {

void outerMethod() {

class LocalInner {

void msg() {

System.out.println("Local inner class inside method");

LocalInner obj = new LocalInner();

obj.msg();

public static void main(String[] args) {

Outer ob=new Outer();

ob.outerMethod();

Anonymous Inner Class

A class without a name that is defined and instantiated at the same time, usually used for
implementing interfaces or abstract classes.

10
abstract class Animal {

abstract void sound();

public class Test {

public static void main(String[] args) {

Animal a = new Animal() {

void sound() {

System.out.println("Anonymous inner class: Dog barks");

};

a.sound();

Static Block in Java


A static block in Java is a block of code that runs once when the class is loaded into memory,
before the main method or any object is created.

Syntax of static block

static {
// code to run when class loads
}

Static block runs once when the class is loaded.

It runs before the main() method.

You can have multiple static blocks, and they run in the order they appear in the code.

public class MyClass {

// Static block

static {

System.out.println("Static block is called");

11
}

public static void main(String[] args) {

System.out.println("Main method is called");

Output:

Static block is called

Main method is called

Object as argument Argument to methods:

In Java, you can pass objects as arguments to methods. It allows you to:

Pass complete objects to methods

Access and modify object properties inside the method

Implement code reusability and modular design

Method returning object:

In Java, a method can return an object just like it returns a primitive value. This is useful when you
want a method to create and return a new object or return an existing object after some
processing.

class A1 {

int marks;

A1 set() {

this.marks = 50; // Set marks on current object

return this; // Return current object

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

A1 ob = new A1(); // Only one object created

ob.set(); // Set marks = 50

System.out.println(ob.marks); // Output: 50

Final Keyword in java

The final Keyword in Java is used as a non-access modifier applicable to a variable, a method, or
a class.

The following are different contexts where the final is used:

Variable

Method

Class

Final Variable:

Definition:
A final variable is a constant.

Its value cannot be changed after it is assigned.

final int x = 10;

x = 20; // Error:can't change final variable

Final Method:

Definition:
A final method cannot be overridden by a subclass.

class A {

final void display() {

System.out.println("Hello");

13
}

class B extends A {

// void display() { }//Error: Cannot override final method

Final Class

Definition:
A final class cannot be extended (no subclass can be created from it).

final class Animal {

void sound() {

System.out.println("Animal sound");

class Dog extends Animal { // ❌ Error: Cannot inherit final class

Finalize:
Finalize is a method which is available in object super class. The purpose of the finalize()
method is to release the resources that is allocated by unused object, before removing unused
object by garbage collector.
The general syntax
Protected void finalize()
{
//finalization code here
}
Key points about finalize() method
1. It is invoked each time before the object is garbage collected.
2. This method can be used to perform cleanup processing.

Garbage collection :
Java garbage collector automatically identifies and removes unused objects, freeing up

14
memory in the heap.
 The gc() is found in system and runtime classes.
 It is static method which is used to call finalize before destroying the object.

public class Demo{

protected void finalize() {


System.out.println("object will be destroyed");
}

public static void main(String[] args) {


Demo ob = new Demo();
ob = null;
System.gc(); // Correct method to suggest garbage collection
}
}
this reference
There can be a lot of usage of Java this keyword. In Java, this is a reference variable
that refers to the current object.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Variable argument

In Java, variable arguments (also called varargs) allow you to pass a variable number of

15
arguments to a method. This is useful when you don’t know in advance how many arguments you’ll
need to pass.
Syntax:
returnType methodName(type... variableName)
public class VarArgsExample {

// Method with varargs


static void display(String... names) {
for (String name : names) {
System.out.println(name);
}
}

public static void main(String[] args) {


display("Alice", "Bob"); // 2 arguments
display("John", "Mary", "Steve"); // 3 arguments
display(); // No arguments
}
}

object of one class is used as a member (data member) of another class


In Java, when the object of one class is used as a member (data member) of another class, it is
called Containment or "has-a" relationship.

Syntax:

class A {
// Class A content
}

class B {
A obj = new A(); // Containment: B has an object of A
}

Inheritance in Java
Definition: Inheritance is one of the key features of OOP that allows us to create a
new class from an existing class. The new class that is created is known as subclass
(child or derived class) and the existing class from where the child class is derived is
known as superclass (parent or base class).

Why use inheritance in java


 For Method Overriding.

16
 For Code Reusability.

Terms used in Inheritance


 Class: It is a template or blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported through
interface.

Single Inheritance: When a class inherits another class, it is known as a single


inheritance. In the example given below, student class inherits the
student_marks class, so there is the single inheritance.

17
The general format is
class superclass_name
{
}
class subclass_name extends superclass_name
{
}

Multi-Level Inheritance
In Multi-Level Inheritance in Java, a class extends to another class that is already
extended from another class. For example, if there is a class A that extends class B and
class B extends from another class C, then this scenario is known to follow Multi-level
Inheritance.

Example
class A
{
}
class B extends A
{
}
class C extends B
{

18
}

Hierarchical inheritance
In Hierarchical Inheritance in Java, more than one derived class extends a single base
class. In simple words, more than one child class extends a single parent class or a single
parent class has more than one child class.

Example:
Class A
{
}
class B extends A
{
}
class C extends A
{
}
Note: In java Multiple inheritance and Hybrid inheritance is not supported. Through
interfaces it will support.

Multiple Inheritance //Multiple Inheritance Through Interfaces in Java//Implementing multiple


interfaces
In Multiple inheritances, one class can have more than one superclass and inherit features from all
parent classes.
Note : Java does not support multiple inheritances with classes. In Java, we can achieve multiple

19
inheritances only through Interfaces.

interface LandVehicle {
default void landInfo() {
System.out.println("This is a LandVehicle");
}
}
interface WaterVehicle {
default void waterInfo() {
System.out.println("This is a WaterVehicle");
}
}
// Subclass implementing both interfaces
class AmphibiousVehicle implements LandVehicle, WaterVehicle {
AmphibiousVehicle() {
System.out.println("This is an AmphibiousVehicle");
}
}
public class Test {
public static void main(String[] args) {
AmphibiousVehicle obj = new AmphibiousVehicle();
obj.waterInfo();
obj.landInfo();
}
}

Hybrid Inheritance

20
In Java, the hybrid inheritance is the composition of two or more types of inheritance. The main
purpose of using hybrid inheritance is to modularize the code into well-defined classes. It also
provides code reusability. The hybrid inheritance can be achieved by using the following inheritance
combinations:

o Single and Multiple Inheritance (not supported, but can be achieved through interface)
o Multilevel and Hierarchical Inheritance
o Hierarchical and Single Inheritance
o Multiple and Multilevel Inheritance

Example:

Object class
Object class is present in java.lang package. Every java class is directly or indirectly
derived from the object class. If a class does not extend any other class then it is
direct child class of object and if extends other class then it is an indirectly derived.
Therefore the object class methods are available to all java classes. Hence object class acts as
a root of inheritance hierarchy in any java program.
The general syntax is

Object obj=getObject();

21
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism means
many forms.
There are two types of polymorphism in Java:
 Compile-time polymorphism (Static Binding)
 Runtime polymorphism(Dynamic Binding)
We can perform polymorphism in java by method overloading and method overriding.

 Runtime Polymorphism in Java


It is also known as dynamic polymorphism. This type of polymorphism is
achieved by function overriding.The method that gets executed is
decided at runtime based on the object's actual class.

Overriding Methods
In Java, method overriding occurs when a subclass (child class) has the same method
as the parent class.

//Example of run time polymorphism


class Bike
{
void run()
{
System.out.println("running");}
}
class Splendor extends Bike
{
void run()
{
System.out.println("running safely with 60km");
}

public static void main(String args[])


{
Bike b = new Splendor();//upcasting
b.run();
}
}

22
Output: running safely with 60km.

 Compile-time polymorphism
It is also known as static polymorphism. This type of polymorphism is achieved by
function overloading or operator overloading.The method to be executed is decided at
compile time based on its parameters and signature.

Method Overloading: When there are multiple functions with the same name but
different parameters then these functions are said to be overloaded.
Functions can be overloaded by change in the number of arguments or/and a change in
the type of arguments.
Syntax:
class A
{
void add(int x,int y)
{System.out.println(“integer values”+(x+y));}
void add(double x,double y)
{System.out.println(“integer values”+(x+y));}
publlic static void main(String args[])
{ A ob=new A();
ob.add(10,20);
ob.add(2.3,4.5);
}

Dynamic Method Dispatch


Definition:
Dynamic Method Dispatch is a process in Java where the method that is to be called is
determined at runtime, not at compile time. It is used to achieve runtime polymorphism.

 Works only with method overriding (not overloading).


 The reference is of the parent class, but the object is of the child class.
 The method of the child class is executed (if overridden), even though the reference is of the
parent.

Difference Between Method Overloading and Method Overriding

Method overloading Method overriding


Method overriding occurs in two classes
Method overloading is performed within class.
that have inheritance relationship.

23
In case of method overloading, parameter must In case of method overriding, parameter
be different. must be same.
Method overloading is the example of compile Method overriding is the example of run
time polymorphism. time polymorphism.
Return type can be same or different in method Return type must be same in method
overloading. But you must have to change the overriding.
parameter.
Syntax: Syntax:
class A class A
{ {
void add(int x,int y) void disp()
{} {}
void add(double x,double y) }
{} class B extends A
} {
void disp()
{}
}

Casting objects
There are two types of casting
d) Upcasting
e) Downcasting

Upcasting
 The process of casting an object of child class to the parent class is called
Upcasting.
 Upcasting can be done implicitly or explicitly.
Downcasting in Java
 Downcasting can be considered as the reverse of Upcasting. We are
typecasting an object of the parent class to the child class.
 Downcasting is not done implicitly by the compiler.

Abstract class
In Java, abstraction can be achieved using abstract classes and methods. A class
which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).

24
Key points of abstract class

 We cannot create object for abstract class.


 We can give abstract class as reference variable
 To use an abstract class you have to inherit it from subclass.
 An abstract class can have a data member, abstract method, method body
(non- abstract method), constructor, and even main() method.

The general syntax


abstract class classname

Abstract Methods in Java


An abstract method is a method that is declared without a body (i.e., no implementation) and ends
with a semicolon

abstract void show(); // No method body

Used only in abstract classes (or interfaces).

Example:

abstract class Animal {

abstract void sound(); // Abstract method

class Dog extends Animal {

void sound() {

System.out.println("Dog barks");

public class Test {

public static void main(String[] args) {

25
Animal a = new Dog(); // Upcasting

a.sound(); // Outputs: Dog barks

Partial Implementation of an Interface in Java

When a class does not implement all the methods of an interface, it must be declared as an
abstract class.

interface Shape { // interface

void draw();

void color();

abstract class Circle implements Shape { //Partial implementation in Abstract class

public void draw() {

System.out.println("Drawing Circle");

// color() method is not implemented here

class RedCircle extends Circle { //Complete Implementation in Subclass:

public void color() {

System.out.println("Coloring Circle Red");

public class Test { // Main Class:

public static void main(String[] args) {

Shape s = new RedCircle();

26
s.draw(); // Output: Drawing Circle

s.color(); // Output: Coloring Circle Red

Extending Interfaces:

Just like classes can extend other classes, interfaces can extend other interfaces using the extends
keyword.

A child interface can inherit methods from one or more parent interfaces.

A class implementing the child interface must implement all methods from both parent and child
interfaces.

interface A {

void show();

interface B extends A {

void display();

class Demo implements B {

public void show() {

System.out.println("Hello from show()");

public void display() {

System.out.println("Hello from display()");

public class Test {

public static void main(String[] args) {

27
Demo obj = new Demo();

obj.show(); // Output: Hello from show()

obj.display(); // Output: Hello from display()

Polymorphism through Interfaces in Java

Polymorphism means "many forms". In Java, polymorphism through interfaces allows one interface
to be used with multiple implementing classes.

// Interface

interface Animal {

void sound(); // abstract method

// Class 1

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks");

// Class 2

class Cat implements Animal {

public void sound() {

System.out.println("Cat meows");

28
// Main class

public class TestPolymorphism {

public static void main(String[] args) {

Animal a; // interface reference

a = new Dog(); // reference to Dog object

a.sound(); // Output: Dog barks

a = new Cat(); // reference to Cat object

a.sound(); // Output: Cat meows

Abstract methods:
In Java, an abstract method is a method that is declared without an implementation. It means
that the method does not have a body and is intended to be overridden by subclasses. Abstract
methods can only exist within an abstract class or an interface.
Example: abstract void display();

abstract class fruit


{
abstract void taste(); //abstract method here not implementing
}

Interfaces in java :

Definition: An interface is a fully abstract class. It includes a group of abstract methods


(methods without a body).
We use the interface keyword to create an interface in Java.

The general syntax is


interface interfaceName
{
Variable declaration;
Method declaration;
29
}

Implementing interfaces
Interfaces are used as “superclasses” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.
The general syntax is
class className implements interfacename
{
//body of the classname
}
Here the class className “implements” the interface interfacename.

Difference between class and interface

Class Interface

The interface cannot contain


Class can contain concrete(with
concrete(with implementation) methods
implementation) methods

Keyword used: class Keyword used: interface


Class includes a constructor Interfaces do not have a constructor
Class stores complete method Interface stores only the signature of
definition a method

Strings and StringBuffer class in Java

Feature String StringBuffer


Mutability Immutable (cannot be changed) Mutable (can be changed)
Performance Slower for many modifications Faster for repeated modifications
Thread Safety Not thread-safe Thread-safe (synchronized)
Package java.lang.String java.lang.StringBuffer

30
Below are few methods in String class
Method Description Example
length() Returns number of characters s.length()
charAt(int index) Returns char at given index s.charAt(2)
concat(String str) Concatenates strings s.concat("World")
equals(String str) Compares strings (case-sensitive) s.equals("Hello")
equalsIgnoreCase() Ignores case when comparing s.equalsIgnoreCase("hello")
toUpperCase() Converts to upper case s.toUpperCase()

Example:
import java.util.Scanner;
public class Message1 {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);


System.out.println("Enter string:");
String str = sc.nextLine();

System.out.println("compareTo = " + str.compareTo("hello"));


System.out.println("length = " + str.length());
System.out.println("Upper = " + str.toUpperCase());
System.out.println("Lower = " + str.toLowerCase());
System.out.println("trim = " + str.trim());

if (str.length() > 5) {
System.out.println("charAt(5) = " + str.charAt(5));
} else {
System.out.println("String is too short for charAt(5)");
}
}
}

Output:

Below are few methods in StringBuffer class


Method Description Example
append(String str) Appends string to buffer sb.append("Java")

31
Method Description Example
insert(int offset, str) Inserts string at given index sb.insert(1, "Hi")
replace(start, end, str) Replaces chars from start to end-1 sb.replace(0, 4, "Hi")
delete(start, end) Deletes chars from start to end-1 sb.delete(1, 3)

32

You might also like