Unit II Class Object and Methods
Unit II Class Object 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
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:
Example:
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:
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.
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);
}
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);
}
}
}
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)
Example 1:
class Calculator {
return a + b;
Example 2:
class Calculator {
// Static method
return a + b;
6
public class Main {
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(); }
obj.welcome();
Recursion:
class RecursionExample {
7
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
Nested Classes:
static nested class: Nested classes that are declared static are called static nested classes.
class Outer {
void display() {
8
}
obj.display();
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() {
innerObj.show();
9
}
· 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.
Example
class Outer {
void outerMethod() {
class LocalInner {
void msg() {
obj.msg();
ob.outerMethod();
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 {
void sound() {
};
a.sound();
static {
// code to run when class loads
}
You can have multiple static blocks, and they run in the order they appear in the code.
// Static block
static {
11
}
Output:
In Java, you can pass objects as arguments to methods. It allows you to:
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() {
12
public static void main(String args[]) {
System.out.println(ob.marks); // Output: 50
The final Keyword in Java is used as a non-access modifier applicable to a variable, a method, or
a class.
Variable
Method
Class
Final Variable:
Definition:
A final variable is a constant.
Final Method:
Definition:
A final method cannot be overridden by a subclass.
class A {
System.out.println("Hello");
13
}
class B extends A {
Final Class
Definition:
A final class cannot be extended (no subclass can be created from it).
void sound() {
System.out.println("Animal sound");
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.
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 {
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).
16
For Code Reusability.
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.
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.
Overriding Methods
In Java, method overriding occurs when a subclass (child class) has the same method
as the parent class.
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);
}
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
Example:
void sound() {
System.out.println("Dog barks");
25
Animal a = new Dog(); // Upcasting
When a class does not implement all the methods of an interface, it must be declared as an
abstract class.
void draw();
void color();
System.out.println("Drawing Circle");
26
s.draw(); // Output: Drawing Circle
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();
27
Demo obj = new Demo();
Polymorphism means "many forms". In Java, polymorphism through interfaces allows one interface
to be used with multiple implementing classes.
// Interface
interface Animal {
// Class 1
System.out.println("Dog barks");
// Class 2
System.out.println("Cat meows");
28
// Main class
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();
Interfaces in java :
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.
Class Interface
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) {
if (str.length() > 5) {
System.out.println("charAt(5) = " + str.charAt(5));
} else {
System.out.println("String is too short for charAt(5)");
}
}
}
Output:
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