SlideShare a Scribd company logo
6
Most read
10
Most read
13
Most read
Method, Constructor, Method
Overloading, Method
Overriding, Inheritance
Object Oriented Programming
By: Engr. Jamsher Bhanbhro
Lecturer at Department of Computer Systems Engineering, Mehran
University of Engineering & Technology Jamshoro
9/21/2023 Object Oriented Programming (22CSSECII)
Method
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known
as functions.
• A method declaration is like a blueprint or a signature of a method. It
specifies the method's name, return type, and the types and order of its
parameters, if any. The method declaration provides essential information
about how the method can be called and what it should return.
• Method declaration does not contain the actual code or implementation of
the method. It only defines the method's interface, allowing other parts of
the code to know how to interact with it.
public int calculateSum(int num1, int num2);
9/21/2023 Object Oriented Programming (22CSSECII)
Method
• A method definition, on the other hand, provides the actual implementation
of the method. It contains the statements and logic that the method executes
when it's called.
• The method definition specifies how the method behaves and what it does
when invoked with specific arguments. It contains the code that performs
the desired functionality.
• Here's an example of a method definition in Java:
public int calculateSum(int num1, int num2) {
return num1 + num2;
}
This method takes two (integers) numbers in input and returns sum.
9/21/2023 Object Oriented Programming (22CSSECII)
Method Examples
public class Main {
static void printBatch() {
System.out.println("This is 22CS");
}
public static void main(String[] args)
{
printBatch();
}
}
public class Calculator {
// Method definition for adding two numbers
public int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
public static void main(String[] args) {
// Create an instance of the Calculator class
Calculator calculator = new Calculator();
// Call the add method and store the result in a variable
int result = calculator.add(5, 7);
// Display the result
System.out.println("The sum is: " + result);
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Constructor
• A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes:
• They have the same name as the class and do not have a return type,
not even void. Constructors are used to set up the initial state of an
object when it is created.
• Default Constructor: A default constructor is automatically provided
by the Java compiler if a class does not explicitly define any
constructors.
• It takes no arguments and initializes the object's fields to default values
(e.g., numeric fields to 0, reference fields to null).
9/21/2023 Object Oriented Programming (22CSSECII)
Constructor
• Default Constructor: A default constructor is automatically provided
by the Java compiler if a class does not define any constructors
explicitly. It takes no arguments and typically initializes the object's
fields to default values
public class Math {
public Math(){
System.out.print(“Default Constructor”);
}
public static void main(String[] args) {
Math math = new Math();
}}
9/21/2023 Object Oriented Programming (22CSSECII)
Constructor
• A parameterized constructor accepts one or more parameters as arguments and
initializes the object's fields using those values.
• It allows you to set specific initial values for object attributes when creating an instance of
the class.
• Example:
public class Person {
private String name;
private int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Constructor
• Copy Constructor: A copy constructor is used to create a new object as a copy of an
existing object of the same class.
• It takes an object of the same class as a parameter and initializes the fields of the new
object with the values from the existing object.
• Example:
public class Student {
private String name;
private int age;
// Copy constructor
public Student(Student otherStudent) {
this.name = otherStudent.name;
this.age = otherStudent.age;
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Method Overloading
Method overloading is a feature in Java (and many other programming
languages) that allows you to define multiple methods in a class with
the same name but different parameter lists. Method overloading is
based on the number, type, or order of method parameters. When you
call a method that has been overloaded, the Java compiler determines
the appropriate method to execute based on the arguments provided
during the method call.
9/21/2023 Object Oriented Programming (22CSSECII)
Method Overloading
Here are the key points about method overloading in Java:
• Method Signature: Method overloading is determined by the method's signature,
which includes the method name and the parameter list. The return type is not
considered when overloading methods.
• Different Parameter Lists: To overload a method, you need to have different
parameter lists in terms of the number of parameters, their types, or their order.
• Same Name, Different Behavior: Overloaded methods can have different
behavior based on the type and number of arguments they receive. This allows
you to create methods that perform similar operations but with varying input.
• Compile-Time Resolution: The appropriate overloaded method is selected at
compile time based on the arguments passed to the method call. This is also
known as compile-time polymorphism.
9/21/2023 Object Oriented Programming (22CSSECII)
Method Overloading Example
public class Calculator {
// Method to add two integers
public int add(int num1, int num2) {
return num1 + num2;
}
// Method to add three integers
public int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
// Method to add two doubles
public double add(double num1, double num2) {
return num1 + num2;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result1 = calculator.add(5, 7);
int result2 = calculator.add(5, 7, 10);
double result3 = calculator.add(3.5, 2.7);
System.out.println("Result 1: " + result1);
System.out.println("Result 2: " + result2);
System.out.println("Result 3: " + result3);
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Method Overloading Example
public class Printer {
// Method to print an integer
public void print(int number) {
System.out.println("Printing an integer: " + number);
}
// Method to print a double
public void print(double number) {
System.out.println("Printing a double: " + number);
}
// Method to print a string
public void print(String text) {
System.out.println("Printing a string: " + text);
}
public static void main(String[] args) {
Printer printer = new Printer();
printer.print(42); // Calls the int version
printer.print(3.14159); // Calls the double version
printer.print("Hello, Java!"); // Calls the string version
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Inheritance in Java
• Inheritance is one of the fundamental concepts in object-oriented programming (OOP),
including Java. It allows you to create a new class that is a modified version of an existing
class. The new class inherits the attributes and behaviors (i.e., fields and methods) of the
existing class, which is referred to as the "parent" or "superclass." The new class is known
as the "child" or "subclass.“
Key concepts and features of inheritance in Java:
• Superclass and Subclass: Inheritance establishes an "is-a" relationship between the
superclass and the subclass. For example, if you have a Vehicle superclass, you can create
subclasses like Car and Motorcycle that inherit characteristics from Vehicle.
• Code Reusability: Inheritance promotes code reusability by allowing you to define
common attributes and behaviors in a superclass, which can be inherited by multiple
subclasses. This reduces code duplication.
• Access to Superclass Members: In a subclass, you can access public and protected
members (fields and methods) of the superclass. Private members are not directly
accessible in subclasses.
9/21/2023 Object Oriented Programming (22CSSECII)
Inheritance in Java
• Method Overriding: Subclasses can provide their own implementation
(override) for methods inherited from the superclass. This allows you to
customize the behavior of the inherited methods in the subclass.
• Super Keyword: The super keyword is used to refer to members of the
superclass within the subclass. It is often used to call the superclass
constructor or access overridden methods and fields.
• Constructors in Subclasses: Subclasses can have constructors of their own.
These constructors can call the constructors of the superclass using the
super keyword.
9/21/2023 Object Oriented Programming (22CSSECII)
Inheritance Example
// Superclass (Parent)
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
// Subclass (Child)
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
public class Main {
public static void main(String[]
args) {
Dog dog = new Dog();
dog.eat(); // Inherited from
Animal
dog.bark(); // Defined in Dog
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Inheritance Example
// Superclass (Parent)
class Vehicle {
String brand; int year;
Vehicle(String brand, int year) {
this.brand = brand; this.year = year; }
void start() {
System.out.println("Starting the vehicle."); }
void stop() {
System.out.println("Stopping the vehicle.");
} }
// Subclass (Child)
class Car extends Vehicle {
int numberOfDoors;
Car(String brand, int year, int numberOfDoors) {
super(brand, year); // Call the superclass constructor
this.numberOfDoors = numberOfDoors; }
void honk() {
System.out.println("Honking the car horn.");
} }
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2022, 4);
// Accessing fields from the superclass
System.out.println("Brand: " + myCar.brand);
System.out.println("Year: " + myCar.year);
System.out.println("Number of Doors: " + myCar.numberOfDoors);
// Calling methods from the superclass
myCar.start();
myCar.stop();
// Calling the subclass-specific method
myCar.honk();
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Inheritance (Method Overriding)
• Method overriding is a fundamental concept in object-oriented programming that
allows a subclass (derived class) to provide a specific implementation for a
method that is already defined in its superclass (base class). When a method in the
subclass has the same name, return type, and parameters as a method in the
superclass, it is said to override the superclass method.
Key points about method overriding:
• Inheritance Requirement: Method overriding is closely related to inheritance. It
occurs when one class inherits from another class.
• Same Signature: The overriding method in the subclass must have the same
method signature as the method in the superclass. This includes the method name,
return type, and parameter types and order.
9/21/2023 Object Oriented Programming (22CSSECII)
Inheritance (Method Overriding)
// Superclass (Parent)
class Animal {
void makeSound() {
System.out.println("Animal makes a sound.");
}
}
// Subclass (Child)
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.makeSound(); // Calls the method in
Animal class
dog.makeSound(); // Calls the overridden
method in Dog class
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
Practice Questions
Create a class with two overloaded methods named calculateArea to calculate the area of a square and a
rectangle. Demonstrate their usage.
Write a program that defines a method findMax with overloaded versions to find the maximum of two integers,
two doubles, and two strings (based on their lengths). Test each version of the method.
Create a class with overloaded constructors to initialize an object with default values, one value, and two values.
Demonstrate the use of these constructors.
Develop a class with overloaded print methods to print a message in different formats, such as plain text, bold,
and italic. Show how to use each version of the method.
Implement a class with overloaded calculate methods to perform addition, subtraction, multiplication, and
division of two numbers. Ensure that the methods can handle different numeric types (int, double).
9/21/2023 Object Oriented Programming (22CSSECII)
Practice Questions
Create a class hierarchy for vehicles, with a base class Vehicle and subclasses Car and Motorcycle. Include properties
like make, model, and methods like startEngine and stopEngine. Demonstrate inheritance by creating objects of these
classes.
Define a base class Shape with properties like color and methods like getArea. Create subclasses for different shapes
like Circle, Rectangle, and Triangle. Override the getArea method in each subclass to calculate the area specific to that
shape.
Create a class hierarchy for bank accounts, including a base class BankAccount and subclasses SavingsAccount and
CheckingAccount. Implement methods for deposit, withdrawal, and balance inquiry. Show how inheritance simplifies
code reuse.
Develop a class hierarchy for animals, with a base class Animal and subclasses Mammal, Bird, and Fish. Include
properties like name and methods like move and sound. Demonstrate polymorphism by calling these methods on
objects of different subclasses.
Write a program that models a university with classes like Person, Student, Professor, and Staff. Use inheritance to
establish relationships between these classes and provide appropriate properties and methods for each class.
9/21/2023 Object Oriented Programming (22CSSECII)

More Related Content

PDF
Managing I/O in c++
Pranali Chaudhari
 
PPTX
Classes in c++ (OOP Presentation)
Majid Saeed
 
PDF
Java Thread Synchronization
Benj Del Mundo
 
PPTX
Variables in java.pptx
gomathikalai
 
PPT
11 constructors in derived classes
Docent Education
 
PPTX
Classes and objects in c++
Rokonuzzaman Rony
 
PPTX
Packages in java
Kavitha713564
 
PPTX
Java Constructor
MujtabaNawaz4
 
Managing I/O in c++
Pranali Chaudhari
 
Classes in c++ (OOP Presentation)
Majid Saeed
 
Java Thread Synchronization
Benj Del Mundo
 
Variables in java.pptx
gomathikalai
 
11 constructors in derived classes
Docent Education
 
Classes and objects in c++
Rokonuzzaman Rony
 
Packages in java
Kavitha713564
 
Java Constructor
MujtabaNawaz4
 

What's hot (20)

PPTX
Java if else condition - powerpoint persentation
Maneesha Caldera
 
PPSX
Collections - Array List
Hitesh-Java
 
PDF
itft-Inheritance in java
Atul Sehdev
 
PPTX
virtual function
VENNILAV6
 
PPTX
Garbage collection
Somya Bagai
 
PPT
Applet life cycle
myrajendra
 
PPTX
Constructors in java
chauhankapil
 
PPT
2. operators in c
amar kakde
 
PPTX
Constructors in C++.pptx
Rassjb
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PDF
Class and Objects in Java
Spotle.ai
 
PDF
Java I/o streams
Hamid Ghorbani
 
PPTX
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
PPT
C++ oop
Sunil OS
 
PDF
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
PPTX
Java string handling
Salman Khan
 
PPTX
Encapsulation
Burhan Ahmed
 
PPS
Java Exception handling
kamal kotecha
 
PDF
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Java if else condition - powerpoint persentation
Maneesha Caldera
 
Collections - Array List
Hitesh-Java
 
itft-Inheritance in java
Atul Sehdev
 
virtual function
VENNILAV6
 
Garbage collection
Somya Bagai
 
Applet life cycle
myrajendra
 
Constructors in java
chauhankapil
 
2. operators in c
amar kakde
 
Constructors in C++.pptx
Rassjb
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Class and Objects in Java
Spotle.ai
 
Java I/o streams
Hamid Ghorbani
 
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
C++ oop
Sunil OS
 
Access specifiers (Public Private Protected) C++
vivekkumar2938
 
Java string handling
Salman Khan
 
Encapsulation
Burhan Ahmed
 
Java Exception handling
kamal kotecha
 
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Ad

Similar to Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java (20)

PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
DOCX
Second chapter-java
Ahmad sohail Kakar
 
PPTX
Introduction to OOPs second year cse.pptx
solemanhldr
 
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
PPTX
U2 JAVA.pptx
madan r
 
PPTX
Java class,object,method introduction
Sohanur63
 
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
PPT
Oop java
Minal Maniar
 
PPTX
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
PPTX
Lecture 5
talha ijaz
 
PPT
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
PDF
JAVA-PPT'S.pdf
AnmolVerma363503
 
PPTX
introduction to object oriented programming language java
RitikGarg39
 
PPTX
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
PDF
Dive into Object Orienter Programming and Design Patterns through java
Damith Warnakulasuriya
 
PPTX
Chapter 04 Object Oriented programming .pptx
fikadumeuedu
 
PPT
Object and class
mohit tripathi
 
PPTX
Intro to object oriented programming.pptx
RafiaZafar19
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Second chapter-java
Ahmad sohail Kakar
 
Introduction to OOPs second year cse.pptx
solemanhldr
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
JAVA-PPT'S.pptx
RaazIndia
 
U2 JAVA.pptx
madan r
 
Java class,object,method introduction
Sohanur63
 
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
Oop java
Minal Maniar
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
Lecture 5
talha ijaz
 
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
JAVA-PPT'S.pdf
AnmolVerma363503
 
introduction to object oriented programming language java
RitikGarg39
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
Dive into Object Orienter Programming and Design Patterns through java
Damith Warnakulasuriya
 
Chapter 04 Object Oriented programming .pptx
fikadumeuedu
 
Object and class
mohit tripathi
 
Intro to object oriented programming.pptx
RafiaZafar19
 
Ad

More from Jamsher bhanbhro (14)

PDF
Abstraction in Java: Abstract class and Interfaces
Jamsher bhanbhro
 
PPTX
Regular Expressions in Java.
Jamsher bhanbhro
 
PPTX
Java Arrays and DateTime Functions
Jamsher bhanbhro
 
PPTX
Lect10
Jamsher bhanbhro
 
PPTX
Lect9
Jamsher bhanbhro
 
PPTX
Lect8
Jamsher bhanbhro
 
PPTX
Lect7
Jamsher bhanbhro
 
PPTX
Lect6
Jamsher bhanbhro
 
PPTX
Lect5
Jamsher bhanbhro
 
PPTX
Lect4
Jamsher bhanbhro
 
PPTX
Compiling and understanding first program in java
Jamsher bhanbhro
 
PPTX
Introduction to java
Jamsher bhanbhro
 
PPTX
Caap presentation by me
Jamsher bhanbhro
 
PPTX
Introduction to parts of Computer(Computer Fundamentals)
Jamsher bhanbhro
 
Abstraction in Java: Abstract class and Interfaces
Jamsher bhanbhro
 
Regular Expressions in Java.
Jamsher bhanbhro
 
Java Arrays and DateTime Functions
Jamsher bhanbhro
 
Compiling and understanding first program in java
Jamsher bhanbhro
 
Introduction to java
Jamsher bhanbhro
 
Caap presentation by me
Jamsher bhanbhro
 
Introduction to parts of Computer(Computer Fundamentals)
Jamsher bhanbhro
 

Recently uploaded (20)

PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PDF
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
CDH. pptx
AneetaSharma15
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Tips Management in Odoo 18 POS - Odoo Slides
Celine George
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
RA 12028_ARAL_Orientation_Day-2-Sessions_v2.pdf
Seven De Los Reyes
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Study Material and notes for Women Empowerment
ComputerScienceSACWC
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
CDH. pptx
AneetaSharma15
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 

Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java

  • 1. Method, Constructor, Method Overloading, Method Overriding, Inheritance Object Oriented Programming By: Engr. Jamsher Bhanbhro Lecturer at Department of Computer Systems Engineering, Mehran University of Engineering & Technology Jamshoro 9/21/2023 Object Oriented Programming (22CSSECII)
  • 2. Method • A method is a block of code which only runs when it is called. • You can pass data, known as parameters, into a method. • Methods are used to perform certain actions, and they are also known as functions. • A method declaration is like a blueprint or a signature of a method. It specifies the method's name, return type, and the types and order of its parameters, if any. The method declaration provides essential information about how the method can be called and what it should return. • Method declaration does not contain the actual code or implementation of the method. It only defines the method's interface, allowing other parts of the code to know how to interact with it. public int calculateSum(int num1, int num2); 9/21/2023 Object Oriented Programming (22CSSECII)
  • 3. Method • A method definition, on the other hand, provides the actual implementation of the method. It contains the statements and logic that the method executes when it's called. • The method definition specifies how the method behaves and what it does when invoked with specific arguments. It contains the code that performs the desired functionality. • Here's an example of a method definition in Java: public int calculateSum(int num1, int num2) { return num1 + num2; } This method takes two (integers) numbers in input and returns sum. 9/21/2023 Object Oriented Programming (22CSSECII)
  • 4. Method Examples public class Main { static void printBatch() { System.out.println("This is 22CS"); } public static void main(String[] args) { printBatch(); } } public class Calculator { // Method definition for adding two numbers public int add(int num1, int num2) { int sum = num1 + num2; return sum; } public static void main(String[] args) { // Create an instance of the Calculator class Calculator calculator = new Calculator(); // Call the add method and store the result in a variable int result = calculator.add(5, 7); // Display the result System.out.println("The sum is: " + result); } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 5. Constructor • A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes: • They have the same name as the class and do not have a return type, not even void. Constructors are used to set up the initial state of an object when it is created. • Default Constructor: A default constructor is automatically provided by the Java compiler if a class does not explicitly define any constructors. • It takes no arguments and initializes the object's fields to default values (e.g., numeric fields to 0, reference fields to null). 9/21/2023 Object Oriented Programming (22CSSECII)
  • 6. Constructor • Default Constructor: A default constructor is automatically provided by the Java compiler if a class does not define any constructors explicitly. It takes no arguments and typically initializes the object's fields to default values public class Math { public Math(){ System.out.print(“Default Constructor”); } public static void main(String[] args) { Math math = new Math(); }} 9/21/2023 Object Oriented Programming (22CSSECII)
  • 7. Constructor • A parameterized constructor accepts one or more parameters as arguments and initializes the object's fields using those values. • It allows you to set specific initial values for object attributes when creating an instance of the class. • Example: public class Person { private String name; private int age; // Parameterized constructor public Person(String name, int age) { this.name = name; this.age = age; } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 8. Constructor • Copy Constructor: A copy constructor is used to create a new object as a copy of an existing object of the same class. • It takes an object of the same class as a parameter and initializes the fields of the new object with the values from the existing object. • Example: public class Student { private String name; private int age; // Copy constructor public Student(Student otherStudent) { this.name = otherStudent.name; this.age = otherStudent.age; } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 9. Method Overloading Method overloading is a feature in Java (and many other programming languages) that allows you to define multiple methods in a class with the same name but different parameter lists. Method overloading is based on the number, type, or order of method parameters. When you call a method that has been overloaded, the Java compiler determines the appropriate method to execute based on the arguments provided during the method call. 9/21/2023 Object Oriented Programming (22CSSECII)
  • 10. Method Overloading Here are the key points about method overloading in Java: • Method Signature: Method overloading is determined by the method's signature, which includes the method name and the parameter list. The return type is not considered when overloading methods. • Different Parameter Lists: To overload a method, you need to have different parameter lists in terms of the number of parameters, their types, or their order. • Same Name, Different Behavior: Overloaded methods can have different behavior based on the type and number of arguments they receive. This allows you to create methods that perform similar operations but with varying input. • Compile-Time Resolution: The appropriate overloaded method is selected at compile time based on the arguments passed to the method call. This is also known as compile-time polymorphism. 9/21/2023 Object Oriented Programming (22CSSECII)
  • 11. Method Overloading Example public class Calculator { // Method to add two integers public int add(int num1, int num2) { return num1 + num2; } // Method to add three integers public int add(int num1, int num2, int num3) { return num1 + num2 + num3; } // Method to add two doubles public double add(double num1, double num2) { return num1 + num2; } public static void main(String[] args) { Calculator calculator = new Calculator(); int result1 = calculator.add(5, 7); int result2 = calculator.add(5, 7, 10); double result3 = calculator.add(3.5, 2.7); System.out.println("Result 1: " + result1); System.out.println("Result 2: " + result2); System.out.println("Result 3: " + result3); } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 12. Method Overloading Example public class Printer { // Method to print an integer public void print(int number) { System.out.println("Printing an integer: " + number); } // Method to print a double public void print(double number) { System.out.println("Printing a double: " + number); } // Method to print a string public void print(String text) { System.out.println("Printing a string: " + text); } public static void main(String[] args) { Printer printer = new Printer(); printer.print(42); // Calls the int version printer.print(3.14159); // Calls the double version printer.print("Hello, Java!"); // Calls the string version } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 13. Inheritance in Java • Inheritance is one of the fundamental concepts in object-oriented programming (OOP), including Java. It allows you to create a new class that is a modified version of an existing class. The new class inherits the attributes and behaviors (i.e., fields and methods) of the existing class, which is referred to as the "parent" or "superclass." The new class is known as the "child" or "subclass.“ Key concepts and features of inheritance in Java: • Superclass and Subclass: Inheritance establishes an "is-a" relationship between the superclass and the subclass. For example, if you have a Vehicle superclass, you can create subclasses like Car and Motorcycle that inherit characteristics from Vehicle. • Code Reusability: Inheritance promotes code reusability by allowing you to define common attributes and behaviors in a superclass, which can be inherited by multiple subclasses. This reduces code duplication. • Access to Superclass Members: In a subclass, you can access public and protected members (fields and methods) of the superclass. Private members are not directly accessible in subclasses. 9/21/2023 Object Oriented Programming (22CSSECII)
  • 14. Inheritance in Java • Method Overriding: Subclasses can provide their own implementation (override) for methods inherited from the superclass. This allows you to customize the behavior of the inherited methods in the subclass. • Super Keyword: The super keyword is used to refer to members of the superclass within the subclass. It is often used to call the superclass constructor or access overridden methods and fields. • Constructors in Subclasses: Subclasses can have constructors of their own. These constructors can call the constructors of the superclass using the super keyword. 9/21/2023 Object Oriented Programming (22CSSECII)
  • 15. Inheritance Example // Superclass (Parent) class Animal { void eat() { System.out.println("Animal is eating."); } } // Subclass (Child) class Dog extends Animal { void bark() { System.out.println("Dog is barking."); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); // Inherited from Animal dog.bark(); // Defined in Dog } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 16. Inheritance Example // Superclass (Parent) class Vehicle { String brand; int year; Vehicle(String brand, int year) { this.brand = brand; this.year = year; } void start() { System.out.println("Starting the vehicle."); } void stop() { System.out.println("Stopping the vehicle."); } } // Subclass (Child) class Car extends Vehicle { int numberOfDoors; Car(String brand, int year, int numberOfDoors) { super(brand, year); // Call the superclass constructor this.numberOfDoors = numberOfDoors; } void honk() { System.out.println("Honking the car horn."); } } public class Main { public static void main(String[] args) { Car myCar = new Car("Toyota", 2022, 4); // Accessing fields from the superclass System.out.println("Brand: " + myCar.brand); System.out.println("Year: " + myCar.year); System.out.println("Number of Doors: " + myCar.numberOfDoors); // Calling methods from the superclass myCar.start(); myCar.stop(); // Calling the subclass-specific method myCar.honk(); } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 17. Inheritance (Method Overriding) • Method overriding is a fundamental concept in object-oriented programming that allows a subclass (derived class) to provide a specific implementation for a method that is already defined in its superclass (base class). When a method in the subclass has the same name, return type, and parameters as a method in the superclass, it is said to override the superclass method. Key points about method overriding: • Inheritance Requirement: Method overriding is closely related to inheritance. It occurs when one class inherits from another class. • Same Signature: The overriding method in the subclass must have the same method signature as the method in the superclass. This includes the method name, return type, and parameter types and order. 9/21/2023 Object Oriented Programming (22CSSECII)
  • 18. Inheritance (Method Overriding) // Superclass (Parent) class Animal { void makeSound() { System.out.println("Animal makes a sound."); } } // Subclass (Child) class Dog extends Animal { @Override void makeSound() { System.out.println("Dog barks."); } } public class Main { public static void main(String[] args) { Animal animal = new Animal(); Dog dog = new Dog(); animal.makeSound(); // Calls the method in Animal class dog.makeSound(); // Calls the overridden method in Dog class } } 9/21/2023 Object Oriented Programming (22CSSECII)
  • 19. Practice Questions Create a class with two overloaded methods named calculateArea to calculate the area of a square and a rectangle. Demonstrate their usage. Write a program that defines a method findMax with overloaded versions to find the maximum of two integers, two doubles, and two strings (based on their lengths). Test each version of the method. Create a class with overloaded constructors to initialize an object with default values, one value, and two values. Demonstrate the use of these constructors. Develop a class with overloaded print methods to print a message in different formats, such as plain text, bold, and italic. Show how to use each version of the method. Implement a class with overloaded calculate methods to perform addition, subtraction, multiplication, and division of two numbers. Ensure that the methods can handle different numeric types (int, double). 9/21/2023 Object Oriented Programming (22CSSECII)
  • 20. Practice Questions Create a class hierarchy for vehicles, with a base class Vehicle and subclasses Car and Motorcycle. Include properties like make, model, and methods like startEngine and stopEngine. Demonstrate inheritance by creating objects of these classes. Define a base class Shape with properties like color and methods like getArea. Create subclasses for different shapes like Circle, Rectangle, and Triangle. Override the getArea method in each subclass to calculate the area specific to that shape. Create a class hierarchy for bank accounts, including a base class BankAccount and subclasses SavingsAccount and CheckingAccount. Implement methods for deposit, withdrawal, and balance inquiry. Show how inheritance simplifies code reuse. Develop a class hierarchy for animals, with a base class Animal and subclasses Mammal, Bird, and Fish. Include properties like name and methods like move and sound. Demonstrate polymorphism by calling these methods on objects of different subclasses. Write a program that models a university with classes like Person, Student, Professor, and Staff. Use inheritance to establish relationships between these classes and provide appropriate properties and methods for each class. 9/21/2023 Object Oriented Programming (22CSSECII)