Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java Programming Unit-2 Mega Notes (1)

The document provides comprehensive notes on Java programming, focusing on inheritance, interfaces, and packages. It covers various types of inheritance (single, multilevel, hierarchical), method overriding, the use of the 'super' keyword, and the definition and implementation of interfaces. Additionally, it discusses abstract classes and methods, emphasizing their role in object-oriented design and code reusability.

Uploaded by

s.saloni1213
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Programming Unit-2 Mega Notes (1)

The document provides comprehensive notes on Java programming, focusing on inheritance, interfaces, and packages. It covers various types of inheritance (single, multilevel, hierarchical), method overriding, the use of the 'super' keyword, and the definition and implementation of interfaces. Additionally, it discusses abstract classes and methods, emphasizing their role in object-oriented design and code reusability.

Uploaded by

s.saloni1213
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

🌟 DiplomaTech Academy 🌟

📘 Java Programming (314317)


Unit II: Inheritance, Interface, and Packages Notes
Mohade Sir

📌 Syllabus 📚

r
Si
🌟 Concept of inheritance​
●​ 2.1 Inheritance:​

📚 Types of inheritance:
○​ Single inheritance
○​ Multilevel inheritance
de
⚙️ 🔒 ✨ use of
○​ Hierarchical inheritance​

🛠️
Method overriding, final variables and methods,
super, abstract methods and classes

💡
●​ 2.2 Interfaces:​

🔗
a
Defining an interface​

📂
Implementing interfaces​

🔄
Accessing interface variables and methods​
oh

Extending interfaces

📦
●​ 2.3 Packages:​

📚
Defining packages​

✏️
Types of packages​
M

📂 🏷️ 📌
Naming and creating packages​

🖇️
Accessing packages, import statement, static import​
Adding classes and interfaces to a package

📞 Made by Mohade Sir


📌 Contact: 8261884261
2.1 🌟 Inheritance in Java
Inheritance is a key concept in Object-Oriented Programming (OOP) that allows
one class (child/subclass) to inherit the properties and methods of another class
(parent/superclass). It promotes code reuse, modularity, and hierarchical
classification.

r
Key Points:

Si
1.​ Code Reusability: Inheritance enables the reuse of code written in the parent
class, reducing redundancy.
2.​ Modularity: Helps organize classes in a hierarchical manner, improving
clarity and maintainability.
de
3.​ Polymorphism: Enables method overriding to achieve dynamic behavior
based on object types.
a
📚 Types of Inheritance in Java
oh

1. Single Inheritance

❖​One child class inherits from one parent class.


❖​Promotes a simple and direct relationship between classes.
M

❖​Helps in creating a clear and straightforward structure for small projects.


❖​Ensures code reuse by allowing the child class to use the methods and
properties of the parent class.
❖​Simplifies maintenance as changes in the parent class automatically reflect
in the child class, reducing redundancy.

// syntax
class Parent {
// Parent class members
}
class Child extends Parent {
// Child class members
}

r
Example:
import java.util.*;

Si
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
de
}
// Child class
class Dog extends Animal {
a
void bark() {
System.out.println("The dog barks.");
oh

}
}
public class SingleInheritanceExample {
M

public static void main(String[] args) {


Dog myDog = new Dog(); // Object of child
class
myDog.eat(); // Access parent class method
myDog.bark(); // Access child class method
}
}
Output:

Animals eat food.

Dogs bark.

r
Multilevel Inheritance

Si
❖​A class inherits from a class, which in turn inherits from another class.
❖​Allows properties to flow across multiple generations.
❖​Useful in scenarios where hierarchy plays an important role, such as
organizational structures.
de
❖​Promotes code reusability across multiple levels of inheritance, reducing
duplication.
❖​Provides better modularity as classes can be divided into smaller,
manageable units across levels.
❖​Supports method overriding at different levels, allowing customization of
a
inherited behaviors.
oh

//sntax
class Grandparent {
// Members
}
M

class Parent extends Grandparent {


// Members
}
class Child extends Parent {
// Members
}
Example:

import java.util.*;
// Grandparent class
class Vehicle {
void start() {
System.out.println("Vehicle starts.");

r
}

Si
}
// Parent class
class Car extends Vehicle {
void drive() {
de
System.out.println("Car drives.");
}
}
// Child class
a
class SportsCar extends Car {
void race() {
oh

System.out.println("Sports car races.");


}
}
public class MultilevelInheritanceExample {
M

public static void main(String[] args) {


SportsCar myCar = new SportsCar(); // Object
of child class
myCar.start(); // Access grandparent class
method
myCar.drive(); // Access parent class method
myCar.race(); // Access child class method
}
}

Output:

Vehicle starts.

Car drives.

r
Si
Sports car races.

Hierarchical Inheritance
de
❖​Multiple child classes inherit from a single parent class.

❖​Promotes shared functionality in the parent class while allowing


customization in child classes.
❖​Useful in modeling general-to-specific relationships (e.g., shapes, vehicles).
a
❖​Encourages modularity, making it easier to extend and manage the codebase.
❖​Reduces redundancy as common attributes and methods are defined once in
oh

the parent class.


❖​Supports scalability, as new child classes can be added without altering the
existing parent class.

//Syntax
M

class Parent {
// Members
}
class Child1 extends Parent {
// Members
}
class Child2 extends Parent {
// Members

Example:

r
import java.util.*;

Si
// Parent class
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
de
}
// Child class 1
a
class Circle extends Shape {
void area() {
oh

System.out.println("Area of circle = πr²");


}
}
// Child class 2
M

class Rectangle extends Shape {


void area() {
System.out.println("Area of rectangle = length
× breadth");
}
}
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();

myCircle.draw(); // Access parent class method


myCircle.area(); // Access child class method

myRectangle.draw(); // Access parent class

r
method

Si
myRectangle.area(); // Access child class
method
}
}
de
Output:
a
Drawing a shape.

Area of circle = πr²


oh

Drawing a shape.

Area of rectangle = length × breadth


M

⚙️ Method Overriding
❖​Dynamic Behavior: Allows redefining a parent class method in a child class
to give it specific behavior.
❖​Polymorphism: Enables dynamic method dispatch, allowing method calls to
be resolved at runtime.
❖​Rules: Overridden methods must have the same signature, and the
@Override annotation is recommended.
❖​Access Control: The access modifier of the overridden method in the child
class cannot be more restrictive than the parent class method.
❖​Return Type: Overridden methods can have a covariant return type (a
subclass of the parent class return type).
❖​Object-Oriented Design: Improves code flexibility and maintainability by

r
customizing inherited behaviors.

Si
class Parent {
void display() {
System.out.println("Parent method.");
de
}
}
class Child extends Parent {
@Override
a
void display() {
oh

System.out.println("Child method.");
}
}
M

example
import java.util.*;
class Parent {
void show() {
System.out.println("This is the parent
method.");
}
}

class Child extends Parent {


@Override
void show() {
System.out.println("This is the child

r
method.");

Si
}
}
de
public class MethodOverridingExample {
public static void main(String[] args) {
Parent obj = new Child(); //
a
Polymorphism
obj.show(); // Calls the child class
oh

method
}
}
M


Output:​

Child class method.
🔒 Final Variables and Methods
❖​Final Variables: Once assigned, the value cannot be changed (acts as a
constant).
❖​Final Methods: Prevents child classes from overriding the method.
❖​Final Classes: Prevents other classes from inheriting from it.
❖​Initialization: Final variables must be initialized during declaration or in the
constructor.

r
❖​Efficiency: Final variables are treated as constants, improving performance

Si
as their values are resolved at compile time.
❖​Security: Ensures that critical methods and data are not accidentally
modified, making the program more secure.
❖​ syntax
final int CONSTANT = 10;
final void display() {
de
System.out.println("This is a final method.");
}
a

;
oh

Import java.util.*;

class Example {
final int MAX_VALUE = 100;
M

final void show() {


System.out.println("This is a final method.");
}
}
public class FinalExample {
public static void main(String[] args) {
Example obj = new Example();
System.out.println("MAX_VALUE: " +
obj.MAX_VALUE);
obj.show();
}
}

Output:​

MAX_VALUE: 100

r
Si
This is a final method

✨ Use of super
de
❖​Access Parent Members: The super keyword allows access to parent class
variables or methods hidden by child class members.
❖​Call Parent Constructor: super() is used to call the parent class
a
constructor from a child class.
❖​Avoid Shadowing: Useful when child and parent class members share the
same name.
oh

❖​Invoke Parent Methods: The super keyword can explicitly invoke a parent
class method in cases of method overriding.
❖​Flexible Initialization: Helps in customizing object initialization by calling
the parent constructor with specific arguments.
M

❖​Enhances Code Clarity: Using super clarifies when a parent class member
or constructor is being referenced, reducing ambiguity.

Example:​

import java.util.*;

class Parent {
void show() {
System.out.println("Parent method.");
}
}

class Child extends Parent {


void show() {

r
super.show(); // Calls parent class

Si
method
System.out.println("Child method.");
}
}
de
public class SuperExample {
a
public static void main(String[] args) {
Child obj = new Child();
oh

obj.show();
}
}
M

Output:​

Parent class method.

Child class method.

1.​
🛠️ Abstract Methods and Classes
❖​Abstract Class: Cannot be instantiated; acts as a blueprint for child classes.
❖​Abstract Method: Declared without a body and must be implemented by
child classes.
❖​Flexibility: Promotes code reusability and allows child classes to provide
specific behavior.
❖​Supports Partial Implementation: Abstract classes can include both abstract

r
and concrete methods, allowing shared logic for all subclasses.

Si
❖​Enforces Design Standards: Ensures that subclasses implement essential
methods, maintaining a consistent structure across implementations.
❖​ syntax
abstract class Parent {
abstract void display();
}
de
class Child extends Parent {
void display() {
a
System.out.println("Child class
implementation.");
oh

}
}
M

Example​

import java.util.*;
abstract class Shape {
abstract void draw(); // Abstract method
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing a
circle.");
}

r
}

Si
public class AbstractExample {
public static void main(String[] args) {
de
Shape myShape = new Circle(); //
Polymorphism
myShape.draw(); // Calls the
a
implementation in Circle
}
oh


Output:
M

Drawing a circle.

2.2 Interfaces in Java


💡 Defining an Interface
❖​Definition: An interface is a blueprint of a class that contains abstract
methods (methods without a body).
❖​Purpose: Specifies what a class must do but not how it does it.
❖​Features: Supports multiple inheritance and ensures a contract for
implementing classes.
❖​Variables: Variables in interfaces are public, static, and final by default.
❖​Method Nature: Methods are public and abstract unless declared default or

r
static.
❖​Flexibility: Interfaces separate implementation from design, increasing

Si
modularity.
❖​ syntax
interface InterfaceName {
// Constants de
int CONSTANT_VALUE = 10; // Implicitly public,
static, final

// Abstract methods
a
void method1(); // Implicitly public and abstract
oh

// Default method
default void defaultMethod() {
System.out.println("Default method in
interface.");
M

}
// Static method
static void staticMethod() {
System.out.println("Static method in
interface.");
}
}
🔗 Implementing Interfaces
❖​A class uses the implements keyword to inherit from an interface.
❖​ A class must provide implementations for all abstract methods of the
interface.
❖​ A single class can implement multiple interfaces to achieve multiple
inheritance.

r
❖​Polymorphism: Objects of the implementing class can be referred to by the

Si
interface type, allowing dynamic method invocation.
❖​Loose Coupling: Interfaces promote loose coupling by separating the
implementation from the contract, making the system more flexible and
easier to modify or extend.
de
syntax.

class ClassName implements InterfaceName {

public void method1() {


a
System.out.println("Implementation of
oh

method1.");

}
M

❖​ 📂 Accessing Interface Variables and Methods


❖​Interface variables are accessed using the interface name, as they are static.
Implemented methods are called using the object of the implementing class
❖​. Default methods can also be accessed using the object of the implementing
class.
❖​Constant Behavior: Interface variables are implicitly public, static,
and final, making them constants that can be shared across multiple
classes.
❖​Static Methods: Interface static methods are accessed using the interface
name directly and cannot be overridden by the implementing classes.

🔄 Extending Interfaces

r
Si
❖​An interface can extend another interface using the extends keyword.
❖​This creates a hierarchy of interfaces, allowing better modularity and
design.
❖​A class implementing the child interface must define methods from all
parent interfaces.
de
❖​syntax

interface ParentInterface {
void parentMethod();
a
}
oh

interface ChildInterface extends ParentInterface {


void childMethod();
}
M

class ImplementingClass implements ChildInterface {


public void parentMethod() {
System.out.println("Parent method
implemented.");
}

public void childMethod() {


System.out.println("Child method
implemented.");
}
}
example

import java.util.*; // Import for utility classes

r
(optional)

Si
interface Animal {
int legs = 4; // public, static, final by default
de
void sound(); // Abstract method
void eat(); // Abstract method

default void info() {


a
System.out.println("Animals have different
behaviors.");
oh

static void animalFact() {


System.out.println("Animals are multicellular
M

organisms.");
}
}

// Interface extension
interface WildAnimal extends Animal {
void habitat(); // Additional abstract method
}

// Implementing multiple interfaces


class Tiger implements WildAnimal {
public void sound() {
System.out.println("Tiger roars.");
}

r
public void eat() {

Si
System.out.println("Tiger eats meat.");
}

public void habitat() {


de
System.out.println("Tiger lives in forests.");
}
}
a
public class InterfaceExample {
public static void main(String[] args) {
oh

Tiger tiger = new Tiger();


tiger.sound(); // Calls implemented method
tiger.eat(); // Calls implemented method
tiger.habitat(); // Calls implemented method
M

tiger.info(); // Access default method in


interface

// Access static method directly through


interface
Animal.animalFact();
// Accessing interface variable
System.out.println("Tiger has " + Animal.legs +
" legs.");
}
}

output

r
Tiger roars.

Si
Tiger eats meat.

Tiger lives in forests.

Animals have different behaviors.


de
Animals are multicellular organisms.

Tiger has 4 legs.


a
Key Points
oh

1.​ Interface Variables: Access using InterfaceName.variableName.


2.​ Default and Static Methods: Interfaces can have implemented methods.
3.​ Multiple Inheritance: A class can implement multiple interfaces like
class X implements A, B.
M

4.​ Flexibility: Interfaces support dynamic, modular, and scalable application


development.

2.3 📦 Packages in Java


Packages in Java are used to group related classes, interfaces, and sub-packages.
They help in better organization, avoiding naming conflicts, and providing
controlled access to classes.

📦 Defining Packages
❖​Packages are a way to organize related classes and interfaces together.
❖​They act as containers to avoid naming conflicts and manage a large

r
codebase efficiently.

Si
❖​Every Java class belongs to a package, even if not explicitly defined (default
package).
❖​They allow controlled access to classes using access modifiers like public,
protected, etc.
❖​Java's standard library is organized into predefined packages (e.g.,
java.util, java.io).
de
Syntax:

package packageName;
a
oh

Example:

package mypackage; // Defining a package


M

public class Example {

public void display() {

System.out.println("This is a package
example!");

}
}

📚 Types of Packages

r
1.​ Built-in Packages: Predefined packages provided by Java, like
java.util, java.io.

Si
2.​ User-defined Packages: Created by users to organize custom classes and
interfaces.

Example of Built-in Package:


de
import java.util.Scanner; // Importing java.util
package
a
public class BuiltInPackageExample {
oh

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Enter a number:");
M

int num = sc.nextInt();

System.out.println("You entered: " + num);

}
✏️ Naming and Creating Packages
❖​Packages should follow naming conventions, typically using lowercase
letters (e.g., com.example).

r
❖​Use reverse domain names for unique identification (e.g., org.myapp).

Si
❖​To create a package, include the package keyword as the first line in the
file.
❖​The folder structure should match the package name (e.g., com.example
should be under a folder named com/example).
de
❖​Use the javac command with -d to compile and store package files in the
correct directory.

Example:
a
package mypackage;
oh

public class PackageExample {

public void displayMessage() {


M

System.out.println("Hello from mypackage!");

}
📂 Accessing Packages and 🏷️ Import Statement
1.​ Use the import keyword to use classes from other packages.
2.​ Import specific classes (import packageName.ClassName) or the
entire package (import packageName.*).

r
3.​ Fully qualified names can be used without the import keyword.

Si
Syntax:

import packageName.ClassName; // Specific import

import packageName.*; // Importing the entire package


a de
Example:

import mypackage.PackageExample; // Importing a


oh

user-defined package
M

public class AccessPackage {

public static void main(String[] args) {

PackageExample obj = new PackageExample();

obj.displayMessage(); // Output: Hello from


mypackage!
}

📌 Static Import

r
Si
1.​ Used to access static members of a class without qualifying them with the
class name.
2.​ Improves code readability by omitting class names when accessing static
methods or variables.

Syntax:
de
import static packageName.ClassName.staticMember;
a
Example:
oh

package mypackage;

public class MyClass {


M

public void sayHello() {

System.out.println("Hello from MyClass


in mypackage!");

}
Output:

Value of PI: 3.141592653589793

Square root of 16: 4.0

🖇️ Adding Classes and Interfaces to a Package

r
Si
1.​ Place all related classes and interfaces in the same package for better
organization.
2.​ The package keyword must be the first statement in each file.
3.​ Classes within the same package can directly access each other without
importing.

Example:​
de
File: mypackage/MyClass.java
a
package mypackage;
oh

public class MyClass {

public void sayHello() {


M

System.out.println("Hello from MyClass in


mypackage!");

}
How to Compile and Run with Packages

r
1.​ Compile: javac -d . MyClass.java MainClass.java

Si
2.​ Run: java mypackage.MainClass

de
Created By Mohade Sir and DiplomaTech Academy Team

#DiplomaTechAcademy
a
oh
M
M
oh
ade
Si
r

You might also like