0% found this document useful (0 votes)
3 views20 pages

Method, Constructor, Method Overloading, Method

method java
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)
3 views20 pages

Method, Constructor, Method Overloading, Method

method java
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

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 Calculator {
public class Main {
// Method definition for adding two numbers
static void printBatch() { public int add(int num1, int num2) {

[Link]("This is 22CS"); int sum = num1 + num2;


return sum;
} }
public static void main(String[] args) {
// Create an instance of the Calculator class
public static void main(String[] args)
Calculator calculator = new Calculator();
{
// Call the add method and store the result in a variable
printBatch(); int result = [Link](5, 7);

} // Display the result


[Link]("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(){
[Link](“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) {
[Link] = name;
[Link] = 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) {
[Link] = [Link];
[Link] = [Link];
}
}

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 { public static void main(String[] args) {
// Method to add two integers Calculator calculator = new Calculator();
public int add(int num1, int num2) {
return num1 + num2; int result1 = [Link](5, 7);
} int result2 = [Link](5, 7, 10);
// Method to add three integers double result3 = [Link](3.5, 2.7);
public int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
[Link]("Result 1: " + result1);
}
[Link]("Result 2: " + result2);
// Method to add two doubles
[Link]("Result 3: " + result3);
public double add(double num1, double num2) {
}
return num1 + num2;
}
}

9/21/2023 Object Oriented Programming (22CSSECII)


Method Overloading Example
public class Printer { public static void main(String[] args) {
// Method to print an integer Printer printer = new Printer();
public void print(int number) {
[Link]("Printing an integer: " + number); [Link](42); // Calls the int version
} [Link](3.14159); // Calls the double version
[Link]("Hello, Java!"); // Calls the string version
// Method to print a double }
public void print(double number) { }
[Link]("Printing a double: " + number);
}

// Method to print a string


public void print(String text) {
[Link]("Printing a string: " + text);
}

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)
public class Main {
class Animal {
void eat() { public static void main(String[]
[Link]("Animal is eating."); args) {
}
Dog dog = new Dog();
}
// Subclass (Child) [Link](); // Inherited from
class Dog extends Animal { Animal
void bark() {
[Link]("Dog is barking.");
[Link](); // Defined in Dog
} }
}
}
9/21/2023 Object Oriented Programming (22CSSECII)
// Superclass (Parent)
Inheritance Example
class Vehicle {

String brand; int year; public class Main {


Vehicle(String brand, int year) {
public static void main(String[] args) {
[Link] = brand; [Link] = year; }
Car myCar = new Car("Toyota", 2022, 4);
void start() {
// Accessing fields from the superclass
[Link]("Starting the vehicle."); }
[Link]("Brand: " + [Link]);
void stop() {

[Link]("Stopping the vehicle.");


[Link]("Year: " + [Link]);

} } [Link]("Number of Doors: " + [Link]);


// Subclass (Child) // Calling methods from the superclass
class Car extends Vehicle { [Link]();
int numberOfDoors; [Link]();
Car(String brand, int year, int numberOfDoors) {
// Calling the subclass-specific method
super(brand, year); // Call the superclass constructor
[Link]();
[Link] = numberOfDoors; }
}
void honk() {
}
[Link]("Honking the car horn.");

} }

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) public class Main {
class Animal { public static void main(String[] args) {
void makeSound() { Animal animal = new Animal();
[Link]("Animal makes a sound."); Dog dog = new Dog();
}
} [Link](); // Calls the method in
Animal class
// Subclass (Child)
[Link](); // Calls the overridden
class Dog extends Animal { method in Dog class
@Override }
void makeSound() { }
[Link]("Dog barks.");
}
}

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)

You might also like