0% found this document useful (0 votes)
8 views18 pages

Unit 2 Java Classes and Objects

This document provides an overview of Java programming concepts, focusing on classes, objects, access control, inheritance, polymorphism, encapsulation, and static members. It explains how to create classes and objects, use access modifiers, and implement inheritance and polymorphism through method overloading and overriding. Additionally, it covers the use of the 'this' and 'super' keywords, static members, and introduces interfaces in Java.

Uploaded by

manavpatel76881
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)
8 views18 pages

Unit 2 Java Classes and Objects

This document provides an overview of Java programming concepts, focusing on classes, objects, access control, inheritance, polymorphism, encapsulation, and static members. It explains how to create classes and objects, use access modifiers, and implement inheritance and polymorphism through method overloading and overriding. Additionally, it covers the use of the 'this' and 'super' keywords, static members, and introduces interfaces in Java.

Uploaded by

manavpatel76881
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

Vivekanand College For BCA 403-Java Programming Language

UNIT 2: CLASSES AND OBJECTS


2.1 SIMPLE CLASS, FIELD

 Java is an object-oriented programming language.


 Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
 A Class is like an object constructor, or a "blueprint" for creating objects.
CREATE A CLASS IN JAVA
 To create a class, use the keyword class.
 In this example, we create a class named "My_Class" with a variable x:
public class My_Class
{
int x = 5;
}
2.2 ACCESS CONTROL AND OBJECT CREATION
&
2.3 CONSTRUCTION AND INITIALIZATION
ACCESS CONTROL IN JAVA
In Java, access modifiers are essential tools that define how the members of a class, like
variables, methods, and even the class itself, can be accessed from other parts of our
program.
There are 4 types of access modifiers available in Java:

Private:

class Person
{
// private variable
private String name;
public void setName(String name)
{
[Link] = name; // accessible within class
}
public String getName()
{
return name;

JINAL PATEL 1|Page


Vivekanand College For BCA 403-Java Programming Language

}
}

public class My_Cls


{
public static void main(String[] args)
{
Person p = new Person();
[Link]("Alice");
// [Link]([Link]); // Error: 'name'
// has private access
[Link]([Link]());
}
}
CREATE AN OBJECT IN JAVA
In Java, an object is created from a class. We have already created the class named My_Class,
so now we can use this to create objects.
To create an object of My_Class, specify the class name, followed by the object name, and
use the keyword new:
public class My_Class
{
int x = 5;
public static void main(String[] args)
{
My_Class myObj = new My_Class();
[Link](myObj.x);
}
}
OUTPUT
5
CREATE A MEHOD IN JAVA

public class MethodEx


{
// A STATIC METHOD THAT DOES NOT RETURN A VALUE (VOID) AND TAKES NO PARAMETERS
static void greet()
{
[Link]("Hello, World!");
}
// A STATIC METHOD THAT RETURNS AN INTEGER AND TAKES TWO INTEGER PARAMETERS
static int addNumbers(int a, int b)
{
int sum = a + b;
return sum; // The return statement is mandatory for non-void methods
}
// A NON-STATIC (INSTANCE) METHOD THAT REQUIRES AN OBJECT TO BE CALLED
public String getInfo()

JINAL PATEL 2|Page


Vivekanand College For BCA 403-Java Programming Language

{
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
}

JINAL PATEL 3|Page


Vivekanand College For BCA 403-Java Programming Language

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;

JINAL PATEL 4|Page


Vivekanand College For BCA 403-Java Programming Language

***************************
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.

Compile time Polymorphism (Method-Overloading)


Compile-Time Polymorphism in Java is also known as static polymorphism and also known as
method overloading. This happens when multiple methods in the same class have the same
name but different parameters.
Method overloading means defining multiple methods with the same name but different
parameter lists. The method call is resolved at compile time based on the arguments passed.
Example: Method overloading by changing the number of arguments
// CLASS 1 HELPER CLASS
class Helper

JINAL PATEL 5|Page


Vivekanand College For BCA 403-Java Programming Language

{
// METHOD WITH 2 INTEGER PARAMETERS
static int Multiply(int a, int b)
{
// RETURNS PRODUCT OF INTEGER NUMBERS
return a * b;
}

// METHOD 2 WITH SAME NAME BUT WITH 2 DOUBLE PARAMETERS


static double Multiply(double a, double b)
{
// RETURNS PRODUCT OF DOUBLE NUMBERS
return a * b;
}
}
// CLASS 2 MAIN CLASS
class MyClass
{
// MAIN DRIVER METHOD
public static void main(String[] args)
{
// CALLING METHOD BY PASSING INPUT AS IN ARGUMENTS
[Link]([Link](2, 4));
[Link]([Link](5.5, 6.3));
}
}
Run-time Polymorphism (Method-Overriding)
Runtime Polymorphism in Java is also known as dynamic method dispatch. It occurs when a
method call is resolved at runtime, and it is achieved using method overriding.
Method-Overriding
Method overriding occurs when a subclass provides its own implementation of a method
already defined in its superclass. The method must have the same name, parameters, and
return type.
Note: At runtime, the method that gets executed depends on the actual object type, not the
reference type.
Example: This program demonstrates method overriding in Java, where the Print() method
is redefined in the subclasses (subclass1 and subclass2) to provide specific implementations.
// CLASS 1 HELPER CLASS
class Parent
{
// METHOD OF PARENT CLASS
void Print()
{
[Link]("parent class");
}
}
// CLASS 2 HELPER CLASS

JINAL PATEL 6|Page


Vivekanand College For BCA 403-Java Programming Language

class subclass1 extends Parent


{
// METHOD
void Print()
{
[Link]("subclass1");
}
}
// CLASS 3 HELPER CLASS
class subclass2 extends Parent
{
// METHOD
void Print()
{
[Link]("subclass2");
}
}
// CLASS 4 MAIN CLASS
class MyOverriding
{
// MAIN DRIVER METHOD
public static void main(String[] args)
{
// CREATING OBJECT OF CLASS 1
Parent a;
// NOW WE WILL BE CALLING PRINT METHODS
// INSIDE MAIN() METHOD
a = new subclass1();
[Link]();

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 –

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the variables values.

JINAL PATEL 7|Page


Vivekanand College For BCA 403-Java Programming Language

public class Person


{
private String name; // private = restricted access
// Getter
public String getName()
{
return name;
}
// Setter
public void setName(String newName)
{
[Link] = newName;
}
}
public class Main
{
public static void main(String[] args)
{
Person myObj = new Person();
[Link] = "SY_BCA_A "; // error
[Link]([Link]); // error
}
}
If the variable was declared as public, we would expect the following output:

SY_BCA_A
However, as we try to access a private variable, we get an error:

[Link]: error: name has private access in Person


[Link] = " SY_BCA_A ";
^
[Link]: error: name has private access in Person
[Link]([Link]);
^
2 errors

2.5 THIS AND SUPER KEYWORD

JINAL PATEL 8|Page


Vivekanand College For BCA 403-Java Programming Language

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.

public class Person


{
// FIELDS DECLARED
String name;
int age;

// 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);

JINAL PATEL 9|Page


Vivekanand College For BCA 403-Java Programming Language

[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
}
}

2.6 Static Members, Static block, Static class

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

static int a = 10;


static int b;
// STATIC BLOCK
Static
{
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String[] args)
{
[Link]("from main");
[Link]("Value of a : "+a);
[Link]("Value of b : "+b);
}
}
Static block initialized.
from main
Value of a : 10
Value of b : 40
Static class
A static nested class is a class declared as static inside another class. It can be accessed
without creating an object of the outer class.
class Outer
{
static class Inner
{
void show()
{
[Link]("Static Nested Class Method");
}
}
public static void main(String[] args)
{
[Link] obj = new [Link]();
[Link]();
}
}
Static Nested Class Method

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);
}
}

The area of the rectangle is 30

Multiple Interface:

// DECLARE THE INTERFACES


interface Walkable
{

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

primarily implemented using encapsulation and access modifiers.


Key Concepts
 Security: By preventing direct access to sensitive data from outside the class, data
hiding protects it from unauthorized or accidental modification.

 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

public static void main(String[] args)


{
// THIS WOULD INVOKE THE PARAMETERIZED CONSTRUCTOR
[Link]("First Object");
Geeks geek1 = new Geeks("Sweta", 68);
[Link]("GeekName: " + [Link] + " and GeekId: " + [Link]);
[Link]();
// THIS WOULD INVOKE THE COPY CONSTRUCTOR
Geeks geek2 = new Geeks(geek1);
[Link]("Copy Constructor used Second Object");
[Link]("GeekName: " + [Link] + " and GeekId: " + [Link]);
}
}
2.7.4 Interface with Inheritance

// DEFINE AN INTERFACE FOR ELECTRIC VEHICLES


interface Electric
{
void charge();
}
// DEFINE A BASE CLASS FOR ALL VEHICLES
class Vehicle
{
public void start()
{
[Link]("The vehicle is starting.");
}
public void stop()
{
[Link]("The vehicle is stopping.");
}
}
// DEFINE A CONCRETE CLASS THAT EXTENDS VEHICLE AND IMPLEMENTS ELECTRIC
class ElectricCar extends Vehicle implements Electric
{
// ELECTRICCAR INHERITS START() AND STOP() FROM VEHICLE
// IT MUST ALSO PROVIDE AN IMPLEMENTATION FOR THE CHARGE() METHOD FROM THE ELECTRIC INTERFACE
public void charge()
{
[Link]("The electric car is charging its battery.");
}
}
// MAIN CLASS TO TEST THE IMPLEMENTATION
public class HybridDemo
{
public static void main(String[] args)
{

JINAL PATEL 17 | P a g e
Vivekanand College For BCA 403-Java Programming Language

ElectricCar myCar = new ElectricCar();

// CALL INHERITED METHOD FROM THE VEHICLE SUPERCLASS


[Link]();

// CALL IMPLEMENTED METHOD FROM THE ELECTRIC INTERFACE


[Link]();

// CALL INHERITED METHOD FROM THE VEHICLE SUPERCLASS


[Link]();
}
}
The vehicle is starting.
The electric car is charging its battery.
The vehicle is stopping.

≤≤≤≤φ φ φ φ ≥≥≥≥

JINAL PATEL 18 | P a g e

You might also like