Unit 2 Java Classes and Objects
Unit 2 Java Classes and Objects
Private:
class Person
{
// private variable
private String name;
public void setName(String name)
{
[Link] = name; // accessible within class
}
public String getName()
{
return name;
}
}
{
return "This is an instance method.";
}
public static void main(String[] args)
{
// CALLING A STATIC METHOD DIRECTLY BY ITS NAME
greet(); //CALL GREET
// CALLING A STATIC METHOD WITH PARAMETERS AND STORING THE RESULT
int result = addNumbers(5, 10);
[Link]("The sum is: " + result);
// TO CALL A NON-STATIC METHOD, YOU MUST FIRST CREATE AN OBJECT OF THE CLASS
MethodEx obj = new MethodEx();
String info = [Link]();
[Link](info);
}
}
OUTPUT
Hello, World!
The sum is: 15
This is an instance method.
2.4 INHERITANCE AND POLYMORPHYSAM IN JAVA
2.4.1 Data Encapsulation, Overriding And Overloading Methods
INHERITANCE
Inheritance It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class. In Java, Inheritance means creating new
classes based on existing ones. A class that inherits from another class can reuse the
methods and fields of that class.
class A
{
//STATEMENTS
}
class B extends A
{
//Statements
}
class MYClass
{
public static void main(String args[])
{
//concept Statements
}
}
Example: In the following example, Animal is the base class and Dog, Cat and Cow are
derived classes that extend the Animal class.
File: [Link]
class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
OUTPUT:
barking...
eating...
The Final Keyword
A variable can be declared as final. Doing so prevents its contents from being modified.
This means that you must initialize a final variable when it is declared.
(In this usage, final is similar to const in C/C++/C#.)
For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
***************************
If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:
Syntax:
Final class Vehicle
{
…..
}
Class Car extends Vehicle
{
…..
}
OUTPUT
[Link]: error: cannot inherit from final Vehicle
class Main extends Vehicle {
^
1 error)
POLYMORPHYSM
Polymorphism in Java is the ability of an object to take on many forms, allowing a single
action or method name to be performed in different ways.
{
// METHOD WITH 2 INTEGER PARAMETERS
static int Multiply(int a, int b)
{
// RETURNS PRODUCT OF INTEGER NUMBERS
return a * b;
}
a = new subclass2();
[Link]();
}
}
DATA-ENCAPSULATION
Encapsulation means combining data and the functions that work on that data into a single
unit, like a class.
Encapsulation in Java is a mechanism of wrapping the data (VARIABLES) and code acting on
the data (METHODS) together as a single unit. In encapsulation, the variables of a CLASS will
be hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as DATA HIDING.
To achieve encapsulation in Java –
SY_BCA_A
However, as we try to access a private variable, we get an error:
this keyword
In Java, this is a keyword that refers to the current object, the object whose method or
constructor is being executed. It is mainly used to:
Refer to the current class’s instance variables and methods.
Differentiate between instance variables and local variables when they have the same
name.
Pass the current object as an argument to methods or constructors.
Call one constructor from another within the same class (using this())
Access instance variables and methods of the object on which the method or
constructor is being invoked.
// CONSTRUCTOR
Person(String name, int age)
{
[Link] = name;
[Link] = age;
}
// GET METHOD FOR NAME
public String get_name()
{
return name;
}
// SET METHOD FOR NAME
public void change_name(String name)
{
[Link] = name;
}
// method to print the details of the person
public void printDetails()
{
[Link]("Name: " + [Link]);
[Link]("Age: " + [Link]);
[Link]();
}
// MAIN FUNCTION
public static void main(String[] args)
{
// OBJECTS DECLARED
Person first = new Person("ABC", 18);
Person second = new Person("XYZ", 22);
[Link]();
[Link]();
first.change_name("PQR");
[Link]("Name has been changed to: " + first.get_name());
}
}
super keyword
The super keyword refers to superclass (parent) objects.
It is used to call superclass methods, and to access the superclass constructor.
The most common use of the super keyword is to eliminate the confusion between super-
classes and subclasses that have methods with the same name.
To understand the super keyword, you should have a basic understanding
of Inheritance and Polymorphism.
class Animal
{
// SUPERCLASS (PARENT)
public void animalSound()
{
[Link]("The animal makes a sound");
}
}
class Dog extends Animal
{
// SUBCLASS (CHILD)
public void animalSound()
{
[Link](); // CALL THE SUPERCLASS METHOD
[Link]("The dog says: bow wow");
}
}
public class Main
{
public static void main(String args[])
{
Animal myDog = new Dog(); // CREATE A DOG OBJECT
[Link](); // CALL THE METHOD ON THE DOG OBJECT
}
}
Static Member
JINAL PATEL 10 | P a g e
Vivekanand College For BCA 403-Java Programming Language
The static keyword in Java is used for memory management and belongs to the class rather
than any specific instance. It allows members (variables, methods, blocks, and nested classes)
to be shared among all objects of a class.
Memory is allocated only once when the class is loaded.
No object creation is needed to access static members; use the class name directly.
Static methods and variables can’t access non-static members directly.
Static methods can’t be overridden because they belong to the class, not instances.
A static variable is also known as a class variable. It is shared among all instances of the class
and is used to store data that should be common for all objects.
class Student
{
int rollNo;
String name;
// STATIC VARIABLE
static String Training_Center = "GFG";
Student(int r, String n)
{
rollNo = r;
name = n;
}
void display()
{
[Link](rollNo + " " + name + " " + Training_Center);
}
}
public class GFG
{
public static void main(String[] args)
{
Student s1 = new Student(101, "Ravi");
Student s2 = new Student(102, "Amit");
[Link]();
[Link]();
}
}
101 Ravi GFG
102 Amit GFG
Static Blocks
A static block is executed only once when the class is first loaded into memory. It is often
used to initialize static variables or perform configuration tasks before the main method
executes.
class Geeks
{
// STATIC VARIABLE
JINAL PATEL 11 | P a g e
Vivekanand College For BCA 403-Java Programming Language
2.7 Interfaces
2.7.1 Introduction to Interfaces, Declaration and implementation of Interface
An Interface in Java is an abstract type that defines a set of methods a class must
implement.
An interface acts as a contract that specifies what a class should do, but not how it
should do it. It is used to achieve abstraction and multiple inheritance in Java. We
define interfaces for capabilities (e.g., Comparable, Serializable, Drawable).
JINAL PATEL 12 | P a g e
Vivekanand College For BCA 403-Java Programming Language
A class that implements an interface must implement all the methods of the interface.
Only variables are public static final by default.
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. For example ,
interface Language
{
public void getType();
public void getVersion();
}
Here,
Language is an interface.
It includes abstract methods: getType() and getVersion().
//DECLARING INTERFACE
interface Polygon
{
void getArea(int length, int breadth);
}
// IMPLEMENT THE POLYGON INTERFACE
class Rectangle implements Polygon
{
// IMPLEMENTATION OF ABSTRACT METHOD
public void getArea(int length, int breadth)
{
[Link]("The area of the rectangle is " + (length * breadth));
}
}
class My_Main
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle();
[Link](5, 6);
}
}
Multiple Interface:
JINAL PATEL 13 | P a g e
Vivekanand College For BCA 403-Java Programming Language
void walk();
}
interface Swimmable
{
void swim();
}
// IMPLEMENT THE INTERFACES IN A CLASS
class Duck implements Walkable, Swimmable
{
public void walk()
{
[Link]("Duck is walking.");
}
public void swim()
{
[Link]("Duck is swimming.");
}
}
// USE THE CLASS TO CALL THE METHODS FROM THE INTERFACES
class Main
{
public static void main(String[] args)
{
Duck duck = new Duck();
[Link]();
[Link]();
}
}
Duck is walking.
Duck is swimming.
2.7.2 Inheriting and Hiding concepts.
Data Hiding
Data hiding in Java is a core object-oriented programming (OOP) concept used to restrict
access to an object's internal state, thus protecting data integrity and enhancing security. It is
Data Integrity: It allows developers to control how data is modified, ensuring that only
valid and consistent values are assigned through controlled methods.
JINAL PATEL 14 | P a g e
Vivekanand College For BCA 403-Java Programming Language
Maintainability and Flexibility: Hiding internal implementation details means that the
internal workings of a class can be changed without affecting other parts of the
program that use the class, as long as the public interface remains consistent.
2.7.3 Constructors.
A constructor in Java is a special member that is called when an object is created. It initializes
the new object’s state. It is used to set default or user-defined values for the object's
attributes
A constructor has the same name as the class.
It does not have a return type, not even void.
It can accept parameters to initialize object properties.
Syntax:
class ClassName
{
// CONSTRUCTOR
ClassName()
{
// Initialization code
}
// PARAMETERIZED CONSTRUCTOR
ClassName(dataType parameter1, dataType parameter2)
{
// Initialization code using parameters
}
// COPY CONSTRUCTOR
ClassName(ClassName obj)
{
// Initialization Code To Copy Attributes
}
}
Example:
1. Default Constructor
A default constructor has no parameters. It’s used to assign default values to an object.
If no constructor is explicitly defined, Java provides a default constructor.
import [Link].*;
class Geeks
{
// Default Constructor
Geeks()
{
[Link]("Default constructor");
}
public static void main(String[] args)
JINAL PATEL 15 | P a g e
Vivekanand College For BCA 403-Java Programming Language
{
Geeks hello = new Geeks();
}
}
Default constructor
Note: It is not necessary to write a constructor for a class because the Java compiler
automatically creates a default constructor (a constructor with no arguments) if your
class doesn’t have any.
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want
to initialize fields of the class with our own values, then use a parameterized
constructor.
class Geeks
{
// data members of the class
String name;
int id;
// Parameterized Constructor
Geeks(String name, int id)
{
[Link] = name;
[Link] = id;
}
// Method to display object data
void display()
{
[Link]("GeekName: " + name + " and GeekId: " + id);
}
// main() method — placed inside the same class for
// universal compatibility
public static void main(String[] args)
{
// This will invoke the parameterized constructor
Geeks geek1 = new Geeks("Sweta", 68);
[Link]();
}
}
GeekName: Sweta and GeekId: 68
3. Copy Constructor
Unlike other constructors copy constructor is passed with another object which copies
the data available from the passed object to the newly created object.
class GFG
{
JINAL PATEL 16 | P a g e
Vivekanand College For BCA 403-Java Programming Language
JINAL PATEL 17 | P a g e
Vivekanand College For BCA 403-Java Programming Language
≤≤≤≤φ φ φ φ ≥≥≥≥
JINAL PATEL 18 | P a g e