Method, Constructor, Method Overloading, Method Overriding, Inheritance In Java
jamsher.bhanbhro
182 views
20 slides
Dec 25, 2023
Slide 1 of 20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
About This Presentation
In the PowerPoint presentation "Method, Constructor, Method Overloading, Overriding in Java," I have described key concepts in Java programming, including methods, constructors, method overloading, and method overriding. Each concept is detailed with definitions, explanations, and practica...
In the PowerPoint presentation "Method, Constructor, Method Overloading, Overriding in Java," I have described key concepts in Java programming, including methods, constructors, method overloading, and method overriding. Each concept is detailed with definitions, explanations, and practical examples to demonstrate its application in Java. The presentation aims to provide a clear and concise understanding of these essential Java programming concepts, making it an effective educational resource for learners and programmers.
Size: 152.65 KB
Language: en
Added: Dec 25, 2023
Slides: 20 pages
Slide Content
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
•Amethodis 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
asfunctions.
•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.
publicintcalculateSum(intnum1,intnum2);
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 aspecial methodthat 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)