0% found this document useful (0 votes)
22 views59 pages

Classes and Objects in Java - Updated

Uploaded by

abinshaji
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)
22 views59 pages

Classes and Objects in Java - Updated

Uploaded by

abinshaji
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/ 59

Classes and Objects

Dr. Arul Xavier V.M


Object Oriented Programming using Java
● Java is an object-oriented programming language.
● The core concept of the object-oriented approach is to break
complex problems into smaller objects.
● Object oriented programming is a technique to develop a
software program using classes and objects.
● Other features
● Abstraction
● Encapsulation
● Inheritance
● Polymorphism
What is an object in Java?
● Object is a real world entity that has
their own properties and behaviors.
● Examples:
● It can be physical
▪ chair, bike, marker, pen, table, car, etc.
● It can be logical
▪ customer, student, employee, manager,
person, bank account., etc.
.
Object’s Characteristics
● State or Field:
● represents the data (value) of an object.
● Behavior:
● represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
What is a class in Java ?
● It is a template or blueprint from which objects are
created.
● It defines a new data type.
● object is an instance of a class.
● It is a logical representation of real world objects.
● A class in Java can contain:
● Fields (data)
● Methods (functions)
Structure of a Java Class

class ClassName {
// state or fields or data
// methods
}

Note: public static void main(String arg[]) { } is one of the method of a class,
like that we can include many methods
Design a Java Class
class classname
{
type instance-variable1;
type instance-variable2;
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
type methodnameN(parameter-list) {
// body of method
}
}
Class Contains:
● Instance variable
● A variable which is created inside the class to represent the attribute
or property of an object.
● Instance variable doesn't get memory at compile time.
● It gets memory at runtime when an object or instance is created.
● Method
● A method is like a function which is used to expose the behavior of
an object.
How to design class in Java?
● Consider an object called Car which can be used to
represents any car in real time.
● It contains attributes and methods/functions.
● For eg. Attributes such as
● Name
● Price.. Etc
● To construct such an object, first we need to design the
class which is a template for that object.
● Let’s see how to design a class for such object ‘Car’.
Real time example: object Car
● In real life, a car is an object.
● The car has fields or data, such as
brand, color, price and etc..,
● The car has behavior or methods such as
● Setting all values
● View details about car
● Accessing the individual fields
● Changing the values of fields
Creating class in Java
class Car {
//state or field or instance data..
String brand,color;
double price;

//Methods
void viewDetails() {
System.out.println("Brand: "+brand);
System.out.println("Color: "+color);
System.out.println("Price: "+price);
}
}
public class ShowRoom {
public static void main(String[] args) {

}
}
Creating an Object in Java
● Here is how we can create an object of a class.

className objectVariable = new className();

public class ShowRoom {


public static void main(String[] args) {

Car car1=new Car();


Car car2=new Car();

}
}
Object Creation- Memory Allocation

Stack Memory

Heap Memory

null
null
0.0

car2 null
null
car1
0.0
main
Access Members of a Class
● We can use the referenceVariable along with the .(dot)
operator to access members of a class.
class Car {
//state or field or instance data..
String brand,color; referenceVariable.brand
double price; referenceVariable.color
referenceVariable.price
//Methods
void viewDetails() { referenceVariable.viewDetails()
System.out.println("Brand: "+brand);
System.out.println("Color: "+color);
System.out.println("Price: "+price);
}
}
Access Members of Car class
class Car {
//state or field or instance data..
String brand,color;
double price;

//Methods
void viewDetails() {
System.out.println("Brand: "+brand);
System.out.println("Color: "+color);
System.out.println("Price: "+price); public class ShowRoom {
} public static void main(String[] args) {
} Car car1=new Car();
car1.brand = "Maruti";
car1.color = "Red";
car1.price = 600000;

car1.viewDetails();
}
}
Object Creation- Memory Allocation

Stack Memory

Heap Memory

Maruti
Red
600000
car1

main
Accessing Members of Car class
public class ShowRoom {
public static void main(String[] args) {

Car car1=new Car();


car1.brand = "Maruti";
car1.color = "Red";
car1.price = 600000;
car1.viewDetails();

System.out.println("---------");

Car car2=new Car();


car2.brand = "Suzuki";
car2.color = "Gray";
car2.price = 800000;
car2.viewDetails();
}
}
Object Creation- Memory Allocation

Stack Memory

Heap Memory

Suzuki
Gray
800000

Maruti
car2 Red
600000
car1

main
Exercise: Design a Class and Object
● A company wants to manage basic details of its employees such as:
• Employee ID

• Name

• Department

• Salary

● Develop a program that stores and displays two employee details


using class, object, instance variables and methods.
// Main class
// Employee class
public class EmployeeDemo {
class Employee {
public static void main(String[] args) {
// Instance variables
// Creating two employee objects
int empId;
Employee e1 = new Employee();
String name;
Employee e2 = new Employee();
String department;
double salary;
// Assigning values using method
e1.setDetails(101, "Rahul Sharma", "IT", 55000);
// Method to set employee details
e2.setDetails(102, "Priya Verma", "HR", 48000);
void setDetails(int id, String n, String dept, double sal) {
empId = id;
// Displaying details
name = n;
System.out.println("Employee Details:");
department = dept;
System.out.println("--------------------------");
salary = sal;
e1.displayDetails();
}
e2.displayDetails();
// Method to display employee details
}
void displayDetails() {
}
System.out.println("Employee ID: " + empId);
System.out.println("Name: " + name);
System.out.println("Department: " + department);
System.out.println("Salary: ₹" + salary);
System.out.println("--------------------------");
}
}
Question
Predict the output of the following program?

class Car {
int i;
int j;
}
class Main { Answer:
public static void main(String[] args) {
Car ob = new Car();
0
System.out.println(ob.i); 0
System.out.println(ob.j);
}
}
Constructor in Java
● A constructor in Java is similar to a method that is invoked
when an object of the class is created.
● Unlike Java methods, a constructor has the same name as
that of the class and does not have any return type.
For example, Here, Test() is a constructor. It has the same name as that
class Test { of the class and doesn't have a return type.

Test() {
// constructor body
}
}
Constructors..
● Types of java constructors
● No-Argument Constructor
● Constructor method without any parameters in it.
● Default constructor
● This constructor will be created by compiler if the class does not
have any constructor in it. (Similar to No-Argument Constructor)
● Parameterized constructor
● Constructor method with parameter is called as parameterized
constructor.
No-Argument Constructor
● A no-argument constructor (or no-arg constructor) is a
constructor without any parameters.

● It is used to create an object without passing any values


during object creation.
Example of no-arg constructor
Predict the output?
class Book {
Book() {
System.out.println("No-arg constructor called"); A) Book object created
} No-arg constructor called
}
public class Library { B) No-arg constructor called
public static void main(String[] args) { Book object created
Book b = new Book();
System.out.println("Book object created"); C) No-arg constructor called
}
} D) Book object created

Answer: B) No-arg constructor called


Book object created
Default Constructor
● If we do not create any constructor, the Java compiler
automatically create a no-arg constructor during the execution
of the program.
● This constructor is called default constructor.
Default Constructor - Example
class Student {
String name;
int regno;
}

public class DemoApp {


public static void main(String[] args) {
Student s1=new Student();
System.out.println("Name: "+ s1.name);
System.out.println("Regno: "+ s1.regno);
}
}
Here, we haven't created any constructors. Hence, the Java
compiler automatically creates the default constructor.
Default Constructor
● The default constructor initializes any uninitialized instance
variables with default values.
● boolean – false
● byte, short, int - 0
● long – 0L
● char - \u0000
● float – 0.0f
● double - 0.0
● object - null
Parameterized Constructor
● A Java constructor can also accept one or more parameters.
● Such constructors are known as parameterized constructors
(constructor with parameters).
Parameterized Constructor
Predict the output
class Customer {
String name;
Customer(String data){
name = "Mr." + data;
}
void sayHello() {
System.out.println("Hello "+name);
}
}
class Sample{ A) Hello John
public static void main(String[] args) {
B) Mr. John
Customer obj=new Customer("John");
obj.sayHello(); C) Hello Mr. John
} D) John
}
C) Hello Mr. John
‘this’ keyword
● In java, this is a reference variable that refers to the
current object inside a method or a constructor.
● Usage of java this keyword
● this keyword can be used to refer current class instance variable.
● this keyword can be used to invoke current class method (implicit)
Instance Variable hiding
● this keyword helps to remove conflict between instance
variable and method/constructor local variable.
class Student {
String name; Instance variable hiding problem
int regno;
Here, the instance variables and parameters
Student(String name, int regno){
of constructor are same.
name = name;
regno = regno; So, constructor parameter hides accessibility of
} instance variables, Hence, instance variables
} gets the default values ie. null,0
public class DemoApp {
public static void main(String[] args) {
Student s1=new Student("John",101);
System.out.println(s1.name);
System.out.println(s1.regno);
}
}
this keyword remove instance variable hiding
class Student {
String name;
int regno;

Student(String name,int regno){


this.name = name;
this.regno = regno;
}
}
public class DemoApp {
public static void main(String[] args) {
Student s1=new Student("John",101);
System.out.println(s1.name);
System.out.println(s1.regno);
}
}
Find the output
class Box
{
int length;
Box(int length) {
this.length = length;
}
void printLength() {
System.out.println("Length: " + length); A) Length: 0
} B) Length: 10
} C) Compilation error
public class TestBox { D) Runtime exception
public static void main(String[] args) {
Box b = new Box(10);
b.printLength(); B) Length: 10
}
}
Constructor Overloading

● Constructor overloading in Java means having more than one


constructor in the same class with different parameter lists (i.e., different
number or types of parameters).
● Key Features:-
● All constructors have the same name as the class.
● Differ by number, type, or order of parameters.
● Allows creating objects in different ways.
● It is a form of compile-time polymorphism.
class Box{
int length,width;
Box(){
this.length=0; class Sample {
this.width=0; public static void main(String [] args)
} {
Box(int size){ Box b1=new Box();
this.length = size; Box b2=new Box(10);
this.width = size; Box b3=new Box(5,10);
} }
Box(int length,int width){ }
this.length = length;
this.width = breadth;
}
}
The call to the constructor is depends on the number and type of parameters!!!
Example:- Student class
class Student {
String name;
int age; class Main {
Student() { public static void main(String[] args) {
name = "Unknown"; Student s1 = new Student();
age = 0; Student s2 = new Student("Alice");
} Student s3 = new Student("Bob", 21);
Student(String name) { s1.display();
this.name = name; s2.display();
age = 0; s3.display();
}
}
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Find the output
class Employee {
double salary;
Employee() { class Main {
public static void main(String[] args)
salary = 0; {
} Employee e=new Employee(100.0);
Employee(int data) { System.out.println(e.salary);
}
salary = data; }
}
Employee(double data) { A. 0.0
salary = data; B. 0
} C. 100.0
} D. Compilation Fails

C) 100.0
Which code to be used at line x to correctly execute the code?

class Circle {
int radius;
Circle(int data) {
radius = data;
}
}
class Main { A. Circle obj = new Circle(5.5);
public static void main(String[] args) { B. Circle obj = new Circle(5);
//line x C. Circle obj = new Circle();
System.out.println(obj.radius); D. Circle obj = new Circle(5, 5.5);
}
} B) Circle obj = new Circle(5);
Method Overloading
● Method overloading in Java is a feature that allows a class to have

more than one method with the same name, as long as their
parameter lists are different.
● Methods must have the same name.
● Methods must differ in number of parameters, type of parameters, or order of
parameters.
● Return type can be different, but it alone is not enough to overload a method.
Method Overloading:-Example
Scenario – Method Overloading
Online Shopping – Bill Calculation
● In an online store, you can:
● Place an order by giving the price and quantity.
● Sometimes, there's a discount.
● Other times, you want to calculate the bill for multiple items at once.

Solution:-
We can apply method overloading to create multiple versions of a
calculateBill() method to handle different types of inputs.
Shopping Cart
class ShoppingCart {

public double calculateBill(double price, int quantity) {


return price * quantity;
}

public double calculateBill(double price, int quantity, double discountPercent)


{
double total = price * quantity;
double discount = total * (discountPercent / 100); public class OnlineShoppingDemo {
return total - discount;
public static void main(String[] args) {
}
ShoppingCart cart = new ShoppingCart();
public double calculateBill(double[] itemPrices) { double bill1 = cart.calculateBill(500.0, 2); // No discount
double total = 0;
double bill2 = cart.calculateBill(750.0, 3, 10); // With 10% discount
for (double price : itemPrices) {
total += price; double[] items = {200.0, 350.0, 150.0, 400.0};
} double bill3 = cart.calculateBill(items); // Multiple items(array)
return total; System.out.println("Bill without discount: ₹" + bill1);
}
} System.out.println("Bill with 10% discount: ₹" + bill2);
System.out.println("Bill for multiple items: ₹" + bill3);
}
}
Find the output?
class overload {
int x;
int y;
void add(int a)
{
x = a + 1;
}
void add(int a, int b){ a) 5
}
x = a + 2;
b) 6
} c) 7
class Overload_methods{
public static void main(String args[]) { d) 8
overload obj = new overload();
int a = 0;
obj.add(6);
System.out.println(obj.x); Answer: c) 7
}
}
Assigning object reference to another variable

● When we assign one object reference variable to another


object reference variable, we are not creating a copy of the
object, we are only making a copy of the reference.

Car ob1=new Car();


Car ob2 = ob1;
Assigning object reference to another variable

Car ob1 = new Car();


Car ob2 = ob1;
ob1
Car
object
ob2
Assigning object reference to another variable
What is the output?
class Student {
String name;
}
public class Test {
public static void main(String[] args) { A) Alice
Student s1 = new Student(); B) Bob
s1.name = "Alice"; C) null
D) Compilation Error
Student s2 = s1;
s2.name = "Bob";
Answer: B) Bob
System.out.println(s1.name);
}
}
Access Modifiers
Access Modifiers
● Java provides four types of access modifiers:
● public

● Accessible from anywhere – inside the class, outside the class, within the
package, and outside the package.
● Private

● Accessible only within the class. Cannot be accessed from outside the class.

● default (no keyword)

● Accessible only within the package. Cannot be accessed from outside the
package. If no access modifier is specified, it is default.
● Protected

● Accessible within the package and from outside the package only through a
child class(sub class). Without a child class, it can't be accessed from
outside the package.
public
● The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
class Cake {
public String name;
public int price;

public Cake(String name,int price){


this.name = name;
this.price = price;
}
public void view(){
System.out.println("Name: "+name+"\nPrice: "+price);
}
}
public class Demo {
public static void main(String [] args) {
Cake ob = new Cake("Black Forest",600);
System.out.println("Name: "+ob.name);
System.out.println("Price: "+ob.price);
ob.view();
}
}
private
● The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

Compiler Error!!!
name, price and view() are private
Predict the output
class Employee {
private int id = 101;

public int getId() {


return id; A) 101
} B) 0
} C) Compilation error
public class Company { D) Runtime exception
public static void main(String[] args)
{
Employee emp = new Employee(); Answer: C) Compilation error
System.out.println(emp.id);
}
}
default
● If you do not specify any access level, it will be the
default.
● The access level of a default modifier is only within the
package.
● It cannot be accessed from outside the package.
protected
● The access level of a protected modifier is within the
package and outside the package through only child
class.
● If you do not make the child class, it cannot be
accessed from outside the package.
Practice 1
Scenario:
You are developing a simple banking system. Each customer has a bank account with basic
operations like depositing and withdrawing money.
Task:
1.Create a class BankAccount with the following attributes:
1. String accountHolderName
2. String accountNumber
3. double balance
2.Write a constructor to initialize the account details.
3.Create the following methods:
1. void deposit(double amount) – Adds the amount to the balance.
2. void withdraw(double amount) – Deducts the amount from the balance only if there are
sufficient funds.
3. void displayAccountInfo() – Displays the account details.
4.In the main method:
1. Create two BankAccount objects with initial balances.
2. Perform deposit and withdrawal operations.
3. Display the account details after each transaction.
Practice 2
Scenario:
You are developing a library management system for a college. As part of this system, you need to
manage books in the library. Each book has a title, author, price, and number of copies
available.
Task:
1.Create a Book class with the following properties:
1. String title
2. String author
3. double price
4. int copiesAvailable
2.Write a constructor to initialize the book's details.
3.Write a method called displayDetails() to print the details of a book.
4.Write a method isAvailable() that returns true if copiesAvailable > 0, otherwise false.
5.In the main method:
1. Create two book objects.
2. Display their details.
3. Check if the books are available.

You might also like