SlideShare a Scribd company logo
6
Most read
13
Most read
17
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

What's hot (20)

PPT
Abstract class in java
Lovely Professional University
 
DOCX
Java interface
HoneyChintal
 
PPS
Packages and inbuilt classes of java
kamal kotecha
 
PPTX
Constructor in java
Hitesh Kumar
 
PPT
Interface in java
Lovely Professional University
 
PPTX
Java web application development
RitikRathaur
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
jQuery for beginners
Arulmurugan Rajaraman
 
PPTX
What Is Express JS?
Simplilearn
 
PPTX
Servlets
ZainabNoorGul
 
PPT
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
PPTX
C# Inheritance
Prem Kumar Badri
 
PPTX
Network programming in java - PPT
kamal kotecha
 
PPT
Networking Java Socket Programming
Mousmi Pawar
 
PPTX
Packages in java
Kavitha713564
 
PPTX
Enumeration in c#
Dr.Neeraj Kumar Pandey
 
PDF
Dependency Injection
Giovanni Scerra ☃
 
PPTX
Build web apps with react js
dhanushkacnd
 
PPTX
INHERITANCE IN JAVA.pptx
NITHISG1
 
Abstract class in java
Lovely Professional University
 
Java interface
HoneyChintal
 
Packages and inbuilt classes of java
kamal kotecha
 
Constructor in java
Hitesh Kumar
 
Java web application development
RitikRathaur
 
Java 8 Lambda Expressions
Scott Leberknight
 
jQuery for beginners
Arulmurugan Rajaraman
 
What Is Express JS?
Simplilearn
 
Servlets
ZainabNoorGul
 
C# Inheritance
Prem Kumar Badri
 
Network programming in java - PPT
kamal kotecha
 
Networking Java Socket Programming
Mousmi Pawar
 
Packages in java
Kavitha713564
 
Enumeration in c#
Dr.Neeraj Kumar Pandey
 
Dependency Injection
Giovanni Scerra ☃
 
Build web apps with react js
dhanushkacnd
 
INHERITANCE IN JAVA.pptx
NITHISG1
 

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

PDF
Unit 2 Methods and Polymorphism-Object oriented programming
DhananjaySateesh
 
PDF
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
PPT
Constructors and destructors in C++
RAJ KUMAR
 
PPT
Java programming concept
Sanjay Gunjal
 
PPTX
constactor overloading.pptx Tanisha patel
jenish07102011
 
PDF
OOPS_Lab_Manual - programs using C++ programming language
PreethaV16
 
PPT
Java
Khasim Cise
 
PPTX
21CSC101T best ppt ever OODP UNIT-2.pptx
Anantjain234527
 
PPT
Java
javeed_mhd
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPTX
Constructors and Destructors
Keyur Vadodariya
 
PPTX
How to design an application correctly ?
Guillaume AGIS
 
PPTX
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
PPTX
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
PPTX
Java 102 intro to object-oriented programming in java
agorolabs
 
DOCX
I assignmnt(oops)
Jay Patel
 
PDF
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 
PPT
java02.pptsatrrhfhf https://www.slideshare.net/slideshow/java-notespdf-259708...
atharvtayde5632
 
PPTX
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
DOCX
Lecture11.docx
ASADAHMAD811380
 
Unit 2 Methods and Polymorphism-Object oriented programming
DhananjaySateesh
 
Constructors & Destructors [Compatibility Mode].pdf
LadallaRajKumar
 
Constructors and destructors in C++
RAJ KUMAR
 
Java programming concept
Sanjay Gunjal
 
constactor overloading.pptx Tanisha patel
jenish07102011
 
OOPS_Lab_Manual - programs using C++ programming language
PreethaV16
 
21CSC101T best ppt ever OODP UNIT-2.pptx
Anantjain234527
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
Constructors and Destructors
Keyur Vadodariya
 
How to design an application correctly ?
Guillaume AGIS
 
2 Object-oriented programghgrtrdwwe.pptx
RamaDalabeh
 
CORE JAVA PPT FOR ENGINEERS BBBBBBBBBBBBBBBBBBB
NagarathnaRajur2
 
Java 102 intro to object-oriented programming in java
agorolabs
 
I assignmnt(oops)
Jay Patel
 
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 
java02.pptsatrrhfhf https://www.slideshare.net/slideshow/java-notespdf-259708...
atharvtayde5632
 
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
Lecture11.docx
ASADAHMAD811380
 
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
 
Ad

Recently uploaded (20)

PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Dimensions of Societal Planning in Commonism
StefanMz
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 

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)