Java Programming Unit-2 Mega Notes (1)
Java Programming Unit-2 Mega Notes (1)
📌 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
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
// 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
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
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
Output:
Vehicle starts.
Car drives.
r
Si
Sports car races.
Hierarchical Inheritance
de
❖Multiple child classes inherit from a single 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
r
method
Si
myRectangle.area(); // Access child class
method
}
}
de
Output:
a
Drawing a shape.
Drawing a shape.
⚙️ 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.");
}
}
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
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.");
}
}
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.
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
}
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.
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.
method1.");
}
M
🔄 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
r
(optional)
Si
interface Animal {
int legs = 4; // public, static, final by default
de
void sound(); // Abstract method
void eat(); // Abstract method
organisms.");
}
}
// Interface extension
interface WildAnimal extends Animal {
void habitat(); // Additional abstract method
}
r
public void eat() {
Si
System.out.println("Tiger eats meat.");
}
output
r
Tiger roars.
Si
Tiger eats meat.
📦 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:
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.
System.out.println("Enter a number:");
M
}
✏️ 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
}
📂 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:
user-defined package
M
📌 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;
}
Output:
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
}
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