KEMBAR78
Inheritance, Packages and Interfaces - Unit - 2 | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
7 views68 pages

Inheritance, Packages and Interfaces - Unit - 2

The document discusses key concepts in object-oriented programming, including method overloading, inheritance, and the use of classes and interfaces. It explains method overloading rules, the use of objects as parameters, and the significance of static, nested, and inner classes. Additionally, it covers inheritance types, the super keyword, method overriding, dynamic method dispatch, and abstract classes.

Uploaded by

kiruthika.ncse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views68 pages

Inheritance, Packages and Interfaces - Unit - 2

The document discusses key concepts in object-oriented programming, including method overloading, inheritance, and the use of classes and interfaces. It explains method overloading rules, the use of objects as parameters, and the significance of static, nested, and inner classes. Additionally, it covers inheritance types, the super keyword, method overriding, dynamic method dispatch, and abstract classes.

Uploaded by

kiruthika.ncse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

INHERITANCE, PACKAGES AND

INTERFACES
UNIT - 2
OVERLOADING METHODS
Definition
• Method overloading is a feature in object-
oriented programming that allows a class to
have multiple methods with the same name
but different parameter lists.
Rules for Method Overloading

• Methods must have the same name.


• Methods must differ in: Number of parameters
(e.g., method(int) vs. method(int, int)).
• Type of parameters (e.g., method(int) vs.
method(double)).
• Order of parameters (e.g., method(int, String)
vs. method(String, int)).
• Return type, access modifier, or method body
does not affect overloading.
class Calculator {
// Method 1: Add two integers
int add (int a, int b)
{
return a + b;
}

// Method 2: Add three integers


int add (int a, int b, int c) {
return a + b + c;
}

// Method 3: Add two doubles


double add(double a, double b) {
return a + b;
}

// Method 4: Add an integer and a double


double add (int a, double b) {
return a + b;
}
}
class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();

// Calls add(int, int)


System.out.println("Sum of 5 and 3: " + calc.add(5, 3)); //
Output: 8

// Calls add(int, int, int)


System.out.println("Sum of 1, 2, 3: " + calc.add(1, 2, 3)); //
Output: 6

// Calls add(double, double)


System.out.println("Sum of 5.5 and 3.2: " + calc.add(5.5, 3.2));
// Output: 8.7

// Calls add(int, double)


System.out.println("Sum of 4 and 2.5: " + calc.add(4, 2.5)); //
Output: 6.5
}
}
Explanation of Example

• The Calculator class defines four add methods with the


same name but different parameter lists: add(int, int):
Takes two integers.
• add(int, int, int): Takes three integers.
• add(double, double): Takes two doubles.
• add(int, double): Takes an integer and a double.
• When calc.add(5, 3) is called, the compiler selects
add(int, int) because the arguments are integers. For
calc.add(5.5, 3.2), the compiler selects add(double,
double) due to the double arguments. The method
signatures allow the compiler to resolve the correct
method at compile time, demonstrating static
Objects as Parameters

Definition
In Java, you can pass objects as parameters to
methods. This allows you to share data
between methods and classes.
Simple Explanation:- An object is created and
passed to a method as an argument.
- The method receives the object as a parameter
and can access its properties and methods.
• Passing Objects as Parameters:- An object is
sent to a method.- The method can use and
modify the object's properties.
• In this example, the person object is passed to
the change Name method, which changes the
name property to "John". The change is
reflected in the original object.
Syntax for class, methods, objects,
constructor
• CLASS SYNTAX:
public class Class Name
{
// Attributes (fields)
dataType attributeName;

// Methods
returnType methodName(parameters) {
// Method body
}
}
• OBJECT SYNTAX:
Class Name objectName = new ClassName(); //
Calls the constructor
• METHOD SYNTAX:
public returnType methodName(parameters) {
// Method body
}
• CONSTRUCTOR SYNTAX:
public Class Name(parameters) { // Constructor
has the same name as the class
// Initialization logic
}
• - Class Declaration:
• The declaration of a new class (e.g. class
Student { ... })
• - Object Declaration:
• The creation of a new object instance
(e.g. Student student = new
Student("John", 20);)
• - Method Declaration:
• The declaration of a new method (e.g.
public static void print Student Info(Student
student) { ... })
Passing a Person object as a parameter

// Class Declaration
class Student {
String name;
int age;
// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}}
// Method Declaration
public static void print Student Info(Student student)
{
System.out.println("Name: " + student.name);
System.out.println("Age: " + student.age);
}
public static void main(String[] args) {
// Object Declaration
Student student = new Student("John", 20);
print Student Info(student);
}
1. public class Student {: Declares a new class called
Student.
2. String name; and int age;: Declare two instance
variables name and age to store the student's
name and age.
3. public Student(String name, int age) {: Declares a
constructor to initialize the name and age instance
variables.
4. this.name = name; and this.age = age;: Initialize the
instance variables with the provided values.
5. public void printInfo() {: Declares a method printInfo
to print the student's information.
6. System.out.println("Name: " + name); and
System.out.println("Age: " + age);: Print the
student's name and age to the console.
7. public static void main(String[] args) {:
Declares the main method.
8. Student student = new Student("John", 20);:
Creates a new Student object with name
"John" and age 20.
9. student.printInfo();: Calls the print Info
method on the student object to print its
information.
What is Returning an Object?

Definition:
A method can return an object of a class, just like it
returns primitive types (int, double, etc.).
Purpose: Allows methods to return complex data
(objects) with multiple attributes and behaviors.
Syntax:
ClassName methodName()
{
return object; // Returns an object of ClassName
}
class Student {
String name;
int rollNo;
// Constructor
Public Student(String name, int rollNo) {
this.name = name;
this.rollNo = rollNo;
}
// Method to return a Student object
public Student get Student()
{
return this; // Returns the current object
}}
// main function
public static void main(String[] args) {

// Create a Student object


Student s1 = new Student("Alice", 101);

// Call method to return Student object


Student returned Student = s1.getStudent();

// Access returned object's fields


System.out.println("Name: " + returnedStudent.name);
System.out.println("Roll No: " + returnedStudent.rollNo);
}
}
What are Static, Nested, and Inner Classes?

• Static Class: A nested class marked static, tied


to the outer class, not an instance.
• Nested Class: A class defined inside another
class (includes static and inner classes).
• Inner Class: A non-static nested class, tied to
an instance of the outer class.
• Purpose: Organize code, encapsulate logic,
and control scope.
Static Class:
A class inside another class that can be used without creating an
object of the outer class.
Nested Class:
A class defined inside another class.
Inner Class:
A non-static nested class that is tied to an instance of the outer
class and needs an object of the outer class to be used.
In short:-
Static Class: Independent, can be used directly.
Inner Class: Dependent, needs an object of the outer class.
Nested Class: A general term that includes both static and non-
static (inner) classes.
STATIC METHOD:
• A static method can be accessed without
creating an object of the class first:
public class Main {
// Static method
Static void myStaticMethod() {
System.out.println("Static methods can be called without creating
objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating
objects");
}
// Main method
public static void main(String[ ] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would output an error
Main myObj = new Main(); // Create an object of Main
Inner Classes

• In Java, it is also possible to nest classes (a


class within a class). The purpose of nested
classes is to group classes that belong
together, which makes your code more
readable and maintainable.
• To access the inner class, create an object of
the outer class, and then create an object of
the inner class:
Access Outer Class From Inner Class

• One advantage of inner classes, is that they


can access attributes and methods of the
outer class:
public class University {
// Static class
public static class Department {
public void printDepartment() {
System.out.println("Computer Science Department");
} }
// Inner class (non-static nested class)
public class Student {
public void printStudent() {
System.out.println("John Doe");
} }
public static void main(String[] args) {
// Using static class
University.Department department = new University.Department();
department.printDepartment();
// Using inner class
University university = new University();
University.Student student = university.new Student();
student.printStudent(); } }
What is Inheritance?

• Definition: Mechanism where a subclass


inherits properties and methods from a super
class.
• Purpose:
– Promotes code reuse.
– Establishes class hierarchy.
• Example: Dog
• class inherits from Animal class.
How Inheritance Works
• Syntax :
class Subclass extends Super class { ... }
public class Super class {
// Super class members
}

public class Subclass extends Super class {


// Subclass members, including inherited ones
}
• Key Points:
– Subclass inherits non-private members.
– Can add new methods or override inherited ones.
EXAMPLE:
class Animal {
void eat() //method declaration
{
System.out.println("Animal eats.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks."); }
}
Types of Inheritance

• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance (via interfaces in Java)
• Hybrid Inheritance
Single Inheritance
• Definition: One class inherits from one super class.
• Example: Car extends Vehicle.
class Vehicle {
void start()
{
System.out.println("Vehicle starts."); }
}
class Car extends Vehicle
{
void drive()
{
System.out.println("Car drives.");
}
Multilevel Inheritance
• Definition: Class inherits from a super class, which inherits from another.
• Example: Puppy extends Dog extends Animal.
class Animal {
void eat() {
System.out.println("Eats.");
}
}
class Dog extends Animal {
void bark()
{ System.out.println("Barks.");
}
}
class Puppy extends Dog {
void play()
{ System.out.println("Plays.");
}
}
Syntax for Hierarchical Inheritance

• class ParentClass {
// Parent class members and methods
}

class ChildClass1 extends ParentClass {


// ChildClass1 specific members and methods
}

class ChildClass2 extends ParentClass {


// ChildClass2 specific members and methods
}

class ChildClass3 extends ParentClass {


// ChildClass3 specific members and methods
}
Hierarchical Inheritance
• Definition: Multiple classes inherit from one super class.
• Example: Car and Bike extend Vehicle.
class Vehicle {
void start()
{
System.out.println("Vehicle starts.");
}}
class Car extends Vehicle {
void drive()
{
System.out.println("Car drives.");
}}
class Bike extends Vehicle
{ void ride()
{
System.out.println("Bike rides.");
Multiple Inheritance of Behavior:
• While Java doesn't support multiple inheritance of
implementation through classes, interfaces provide
a way to achieve multiple inheritance of behavior.
• A class can inherit abstract method signatures and
thus behavior requirements from multiple sources.
• Consider a Duck class that needs to have both
Swimmable capabilities and Flyable capabilities. You
could define two interfaces: Swimmable and
Flyable
Multiple Inheritance (Interfaces)
Definition: Class implements multiple interfaces (not classes
in Java).
Example: Class implements Swimmable and Flyable.
Code Example:
interface Swimmable {
void swim();
}
interface Flyable {
void fly();
}
class Duck implements Swimmable, Flyable {
public void swim() { System.out.println("Duck swims."); }
public void fly() { System.out.println("Duck flies."); }
The Super Keyword
• The super keyword in Java is a reference variable used
to refer to the immediate parent class object.
• It is primarily used in the context of inheritance to
access members (variables, methods, and constructors)
of the super class from within a subclass.
Purpose: Refers to the super class in a subclass.
• Uses:
– Call super class constructor:
super(...);
– Access super class methods/fields:
super.MethodName();
– Must be first statement in constructor if used for constructor
call.
Class Parent {
Parent(String name) //constructor declaration
{
System.out.println ("Parent constructor called with: " + name);
}
}

class Child extends Parent {


Child() {
super("Java"); // Calls the Parent's constructor
System.out.println("Child constructor called");
}
}
The super() syntax (with parentheses) is used to call the
constructor of the immediate super class from within a subclass's
constructor. This call must be the very first statement in the
subclass constructor. It is essential for initializing inherited
Super Keyword Example
class Animal //super class
{
String name;
Animal (String name) //constructor declare
{
this.name = name;
}
void eat() { //method declare
System.out.println(name + " eats.");
}}
class Dog extends Animal { //subclass
Dog(String name) { //constructor declare
super(name); // Call super class constructor
}
void eat() //method declare
{
super.eat(); // Call superclass method
System.out.println("Dog eats bones.");
}
What is Method Overriding
• Definition:
• Method overriding, is a feature that allows a
subclass to provide a specific implementation
of a method that is already defined in its super
class.
• Rules:
– Method name, parameters, and return type must
match.
– Access modifier cannot be more restrictive.
– Used to achieve runtime polymorphism.
• Example: Dog overrides Animal’s make Sound().
Method Overriding Example

class Animal
{
void make Sound() { //method
System.out.println("Animal makes a sound.");
}}
class Dog extends Animal {
@Override
void make Sound() {
System.out.println("Dog barks.");
}}
public class Main {
public static void main(String[] args)
{
Animal dog = new Dog(); // object create for super class
dog.make Sound(); // Outputs: Dog barks.
What is Dynamic Method Dispatch?

• Definition: Mechanism where the call to an


overridden method is resolved at runtime,
based on the object’s actual type.
• Key Points:
– Enabled through method overriding.
– Super class reference can hold subclass object.
– Actual method called depends on object’s runtime
type.
• Also Known As: Runtime polymorphism.
Dynamic Method Dispatch Example
class Vehicle
{
void start()
{
System.out.println("Vehicle starts."); } }
class Car extends Vehicle
{
@Override
void start()
{
System.out.println("Car starts with key.");
}}
class Bike extends Vehicle {
@Override
void start()
{
System.out.println("Bike starts with kick.");
}}
public class Main {
public static void main(String[] args)
{
Vehicle vehicle; //Declares a reference variable named vehicle of
type Vehicle.
vehicle = new Car(); //An instance of the Car class is created and assigned
to the vehicle reference.
vehicle.start(); // Outputs: Car starts with key.
vehicle = new Bike();
vehicle.start(); // Outputs: Bike starts with kick.
}
Polymorphism:

• The code demonstrates polymorphism


because the same method call (vehicle.start())
results in different actions based on the
object's actual type at runtime.
• This is achieved by using a common interface
(the Vehicle class) and allowing subclasses to
provide their own implementations of
the start() method.
What are Abstract Classes?
• Definition: A class declared with the abstract
keyword that cannot be instantiated and may
contain abstract methods.
• Features:
– Can have both abstract (no body) and concrete
(with body) methods.
– Subclasses must implement all abstract methods
or be abstract themselves.
– Used to define a common interface and partial
implementation.
• Syntax: abstract class Class Name { ... }
Abstract Class Example
abstract class Shape
{
abstract void draw();
// Abstract method void describe()
{
// Concrete method
System.out.println("This is a shape.");
}}
class Circle extends Shape
{
@Override
void draw()
{
System.out.println("Drawing a circle.");
}
What is the final Keyword?
• Title: Introduction to final Keyword
Content:
• final is a Java keyword used to restrict
modification.
• Applied to:
– Classes: Prevents inheritance.
– Methods: Prevents overriding.
– Variables: Makes them constant.
• Key role in controlling inheritance behavior.
Final Class
Title: Final Class and Inheritance

Content:
• A final class cannot be extended (no subclasses).
• Use case: Ensure class behavior is immutable (e.g.,
String).

Example:
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
public class Main
{
public static void main(String[] args)
{
Shape circle = new Circle();
circle.draw(); // Outputs: Drawing a circle.
circle.describe(); // Outputs: This is a shape.
}
}
Final Method
• Title: Final Method and Inheritance
Content:
• A final method cannot be overridden by subclasses.
• Use case: Protect critical method logic.
Example:
Class Parent {
final void finalMethod() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// Error: void finalMethod() {}
Combining Concepts
• How They Work Together:
– Method Overriding: Enables specific
implementations in subclasses.
– Dynamic Method Dispatch: Resolves overridden
method calls at runtime.
– Abstract Classes: Provide a blueprint with abstract
methods for overriding.
• Example Use Case: A Shape abstract class with
draw() overridden by Circle and Rectangle,
called via dynamic dispatch.
Summary

• Method Overriding: Subclass redefines


superclass method for specific behavior.
• Dynamic Method Dispatch: Runtime
resolution of overridden method calls.
• Abstract Classes: Define common structure
with abstract and concrete methods.
Final Variable
• Final Variable in Inheritance
Content:
• A final variable’s value is constant after initialization.
• Can be inherited but not modified.

Example:
class Example {
final int VALUE = 10;
}
class SubExample extends Example {
void show() {
System.out.println(VALUE); // Prints 10
// VALUE = 20; // Error
}
Conclusion:
• final keyword restricts inheritance in Java:
Classes: No subclassing.
• Methods: No overriding.
• Variables: No reassignment.
• Enhances security, design, and performance.
What Are Packages?

• Content:
• Organize classes/interfaces into namespaces.
• Benefits: Avoid naming conflicts, improve
modularity.
Syntax:
package com.example;
public class MyClass {}
Member Access in Packages

• Content:
• Access Modifiers: public, protected, default, private.
• Example: java
• package com.example;
• public class Parent {
• public int publicVar = 1;
• protected int protectedVar = 2;
• int defaultVar = 3;
• }
• protected: Accessible in subclasses (any package). default:
Same package only.
Importing Packages

• Use import to access classes/interfaces from


other packages.
• Examples: java
• import com.example.Parent;
• import com.example.*;
• import static java.lang.Math.PI;
• Rules: java.lang.* auto-imported, same-
package classes don’t need imports.
Interfaces and Inheritance

• Content:
• Interface: Contract for methods, supports multiple inheritance.
• Example: java
• package com.example;
• public interface MyInterface {
• void abstractMethod();
• default void defaultMethod() { /* ... */ }
• }
• class MyClass implements MyInterface {
• public void abstractMethod() { /* ... */ }
• }
Summary

• Content:
• Packages: Organize code, control access.
• Importing: Simplifies class usage across
packages.
• Interfaces: Enable abstraction, polymorphism.
• Connection to final: Restricts inheritance in
classes implementing interfaces.
• Topics Covered:
• Packages
• Member Access
• Importing Packages
• Interfaces
• Packages in Java
• Title: What Are Packages?
Content:
• Definition: Namespaces to organize classes and interfaces.
• Purpose:
– Avoid naming conflicts
– Group related code
– Enhance modularity
• Syntax:
• package com.example; public class MyClass { // Class code
}
Member Access in Packages

• Title: Controlling Member Access


Content:
• Access Modifiers:
– public: Accessible everywhere
– protected: Same package + subclasses
– default (none): Same package only
– private: Same class only
Example:
package com.example;
public class Parent {
public int publicVar = 1;
protected int protectedVar = 2;
int defaultVar = 3;
private int privateVar = 4;
}
• Importing Packages
• Title: Importing Packages
Content:
• Purpose: Use classes/interfaces from other
packages.
• Syntax:
import com.example.Parent; // Specific class
import com.example.*; // All classes in package
import static java.lang.Math.PI; // Static member
• Rules:
– java.lang.* auto-imported
– Same-package classes don’t need imports
• Example:
• package com.app; import
com.example.Parent; class Test { Parent p =
new Parent(); }
• Interfaces in Java
• Title: Understanding Interfaces
Content:
• Definition: Contract for methods; supports
multiple inheritance.
• Features:
– Abstract methods (implicitly public abstract)
– Default/static methods (Java 8+)
– Constants (implicitly public static final)
• Example:
package com.example;
public interface Vehicle {
void move(); // Abstract
default void honk() { // Default
System.out.println("Honk!");
}}
class Car implements Vehicle {
public void move()
{ System.out.println("Car moves");
}
• Summary and Connection to Inheritance
• Title: Key Takeaways
Content:
• Packages: Organize code, control access via modifiers.
• Importing: Simplifies cross-package usage.
• Interfaces: Enable abstraction, polymorphism.
• Inheritance Link:
– Use final to restrict class/interface implementation.
– Example: final class Car implements Vehicle { ... }

You might also like