KEMBAR78
Unit 2-BCA- Classes, Inheritance & interface .pdf
Unit 2: Classes, Inheritance, Packages &
Interfaces(15)
Classes: Class fundamentals; Methods; Naming conventions; Declaring objects;
Access specifiers; Constructors; Command line arguments; Method Overloading;
keywords: this, final; Static; abstract, finalize.
Inheritance:Single; Multilevel inheritance; Method overriding-Dynamic method
dispatch; Abstract classes, Usage of super.
Interfaces:Defining an interface; Implementing interfaces; Extending interfaces.
Packages:user defined packages; creating and implementing packages.
Definition of Class and Object
Class: A class in Java is a blueprint for creating objects. It contains fields (variables) and methods (functions)
that define the behavior of the objects.
class Student {
int id;
String name;
}
Object: An object is an instance of a class. It is created using the new keyword.
Student s1 = new Student();
2. Fields and Methods
Fields are variables defined inside a class that hold data.
Methods define actions or behavior of the class.
class Student {
int id;
String name;
void display() {
System.out.println(id + " " + name);
}
}
Object Instantiation
Creating an object involves:
○ Declaring a reference variable of the class.
○ Using the new keyword to allocate memory.
Student s1 = new Student(); // Object created
After instantiation, fields can be accessed and methods can be called using the dot (.) operator:
s1.id = 101;
s1.name = "Alice";
● s1.display();
4. Syntax and Naming Conventions
● Class Names: Should begin with an uppercase letter. Example:
Student, Employee.
● Variable and Method Names: Should begin with a lowercase letter
and use camelCase. Example: studentName, displayInfo.
● Use meaningful names to improve readability.
Introduction to Access Specifiers
Access specifiers define the accessibility (visibility) of classes,
fields, constructors, and methods. The main access specifiers in
Java are:
Specifier Access Level
Public Accessible from any class
Private Accessible only within the same class
Protected Accessible within the same package or subclass
(default) Accessible only within the same package
1. public
● Open to everyone.
● Can be accessed from anywhere in your program.
public class A {
public int x = 10;
}
You can access x from any other class.
2. private
● Locked inside the class.
● Can only be used within the same class.
public class A {
private int y = 20;
public void show() {
System.out.println(y); // ✅ allowed here
}
}
You cannot use y from outside the class.
3. protected
● Can be used inside the class, inside the package, and by child classes (subclasses) even if in another package.
public class A {
protected int z = 30;
}
Subclass or same-package class can access z.
4. Default (no keyword)
● If you don’t write anything, it's accessible only in the same package.
class A {
int a = 40; // default access
}
Only other classes in the same package can access a.
Feature Default Protected
Keyword No keyword used Uses protected keyword
Same Class ✅ Accessible ✅ Accessible
Same Package ✅ Accessible ✅ Accessible
Subclass in Same Package ✅ Accessible ✅ Accessible
Subclass in Different
Package
❌ Not accessible ✅ Accessible
Non-subclass in Different
Package
❌ Not accessible ❌ Not accessible
File: A.java (in package1)
package package1;
public class A {
int x = 10; // default
protected int y = 20; // protected
}
File: B.java (in package2, subclass of A)
package package2;
import package1.A;
public class B extends A {
public void show() {
// System.out.println(x); // Error: default not accessible outside package
System.out.println(y); // ✅ OK: protected accessible in subclass
}
}
Constructors & Overloading
A constructor is a special method that is automatically called when an
object is created.
It has the same name as the class and no return type (not even void).
Types of Constructors
Default Constructor
Parameterized Constructor
Default Constructor
● Created by the compiler if no constructor is defined.
● Takes no arguments and sets default values.
class Student {
int id;
String name;
Student() { // Default constructor
id = 0;
name = "Not Assigned";
}
void display() {
System.out.println(id + " " + name);
}}
Parameterized Constructor
● Takes parameters to assign values when object is created.
class Student {
int id;
String name;
Student(int i, String n) { // Parameterized constructor
id = i;
name = n;
}
void display() {
System.out.println(id + " " + name);
}}
3. Constructor Overloading
● Multiple constructors in a class with different parameter lists.
● Helps in creating objects in multiple ways.
class Student {
int id;
String name;
// Default constructor
Student() {
id = 0;
name = "NA";}
// Parameterized constructor
Student(int i, String n) {
id = i;
name = n; }
void display() {
System.out.println(id + " " + name); }}
4. Method Overloading
● Same method name with different parameters (type or number).
● Compile-time polymorphism.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Constructor vs Method
Feature Constructor Method
Name Same as class name Any name
Return Type No return type Must have a return type
Called When Automatically during object
creation
Called manually by object
Purpose Initialize object Perform action
class Book {
String title;
int pages;
// Constructor
Book(String t, int p) {
title = t;
pages = p;
}
// Overloaded method
void display() {
System.out.println(title + " has " + pages + "
pages.");
}
void display(String author) {
System.out.println(title + " by " + author);
}
}
public class Main {
public static void main(String[] args) {
Book b1 = new Book("Java Basics",
250);
b1.display();
b1.display("John");
}
}
Access Specifiers in Java
Access specifiers control the visibility of classes, methods, and variables.
Specifier Accessible
Within Class
Within Package Outside Package
(Subclass)
Outside
Package
public ✔ ✔ ✔ ✔
private ✔ ✘ ✘ ✘
protected ✔ ✔ ✔ ✘
public class Demo {
public int a; // Accessible everywhere
private int b; // Accessible only inside class
protected int c; // Accessible in subclass or same package
int d; // default - package only
}
Command Line Arguments in Java
Command line arguments are values passed to a Java program when it is run from
the command line.
● They are passed during program execution.
● They are stored in the String[] args array in the main() method.
● Useful when you want to provide input without using Scanner or GUI.
Example Program
public class CommandLineExample {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
javac CommandLineExample.java
java CommandLineExample Hello World 123
OUTPUT:
Number of arguments: 3
Argument 0: Hello
Argument 1: World
Argument 2: 123
Method Overloading in Java
Method Overloading means defining multiple methods in the same class with the same name but
different parameters (type, number, or order of parameters).
● To perform different tasks using the same method name.
● Improves code readability and reusability.
To overload a method:
● Method name must be the same.
● Parameters must be different by:
○ Number of parameters
○ Data types of parameters
○ Order of parameters
Return type does not matter in overloading.
public class Calculator {
// Method with one int parameter
void add(int a) {
System.out.println("Sum: " + (a + 10));
}
// Method with two int parameters
void add(int a, int b) {
System.out.println("Sum: " + (a + b));
}
// Method with two double parameters
void add(double a, double b) {
System.out.println("Sum: " + (a + b));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(5); // calls method with
one int
calc.add(5, 10); // calls method with
two ints
calc.add(2.5, 3.5); // calls method
with two doubles
}
}
Output:
Sum: 15
Sum: 15
Sum: 6.0
Benefits of Method Overloading
● Cleaner code
● Same method name for similar operations
● Easier to maintain
keywords: this, final; Static; abstract, finalize.
2. this Keyword
● Refers to current class object.
● Used when local variable name is same as instance variable.
Example:
class Student {
int id;
Student(int id) {
this.id = id; // this refers to instance variable
}}
Without this, the line:
id = id;
would assign the parameter id to itself — which does nothing.
With this:
this.id = id;
…it means:
● this.id → instance variable
● id → constructor parameter
So the instance variable gets the value passed to the constructor.
this.id = id; means:
"Assign the constructor’s id value to the object’s id variable."
final Keyword
● Used to prevent changes.
Usage Meaning
final variable cannot be changed
final method cannot be overridden
final class cannot be inherited
final int x = 10;
// x = 20; Error
final class A { }
// class B extends A {} Error
b. Static Method
● Can be called without creating object.
● Can access only static data.
class MyClass {
static void sayHello() {
System.out.println("Hello from static method!"); }}
public class Test {
public static void main(String[] args) {
MyClass.sayHello(); // No need to create an object
}}
4. final Keyword
● Used to make variable constant, method non-overridable, or class non-inheritable.
a. Final Variable
final int x = 10;
// x = 20; // Error: Cannot change value
b. Final Method
class A {
final void show() {
System.out.println("Final method");
}
}
c. Final Class
final class Vehicle {
}
// class Car extends Vehicle {} // Error: Cannot inherit final class
3. static Keyword
● Used with variables, methods, and blocks.
● Shared by all objects of the class.
a. Static Variable
● One copy shared by all objects.
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println(count);
}}
public class Test {
public static void main(String[] args) {
Counter c1 = new Counter(); // count becomes 1
Counter c2 = new Counter(); // count becomes 2
Counter c3 = new Counter(); // count becomes 3
}
}
5. finalize() Method
● Called by Garbage Collector before object is destroyed.
● Used for cleanup activities.(It is called by the Garbage Collector (GC) before an object is destroyed,
to perform cleanup tasks (like closing files, releasing resources, etc.).)
class Example {
protected void finalize() {
System.out.println("Object is destroyed");
}
}
abstract in Java
An abstract is a keyword used for abstract classes and abstract methods.
● Abstract class:
○ Cannot be directly instantiated (you can’t create an object from it).
○ Can contain abstract methods (methods without a body) and normal methods (methods with code).
● Abstract method:
○ Declared without a body — only the method signature is given.
○ Must be implemented by the subclass.
Why use it?
To create a blueprint for other classes — useful when you want all subclasses to follow a certain structure.
abstract class Animal {
abstract void sound(); // abstract method (no body)
void sleep() { // normal method
System.out.println("Sleeping...");
}}
class Dog extends Animal {
void sound() {
System.out.println("Bark!");
}}
public class Main {
public static void main(String[] args) {
// Animal a = new Animal(); // Cannot create object of abstract class
Animal myDog = new Dog();
myDog.sound(); // Output: Bark!
myDog.sleep(); // Output: Sleeping...
Inheritance in Java
Definition:
Inheritance lets one class (child/subclass) reuse the fields and methods of another class (parent/superclass).
We use the extends keyword.
a) Single Inheritance
One subclass inherits from one superclass.
class Animal {
void eat() {
System.out.println("Eating...");
}}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // From Animal
d.bark(); // From Dog
}}
b) Multilevel Inheritance
A chain of inheritance — one class inherits from another, which inherits from another.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Weeping...");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // From Animal
p.bark(); // From Dog
p.weep(); // From Puppy
}
}
OUTPUT
Eating...
Barking...
Weeping...
Method Overriding & Dynamic Method Dispatch
● Method Overriding: A subclass provides its own version of a method that
already exists in the superclass.
● Dynamic Method Dispatch:
The method that gets called is decided at runtime based on the object type,
not the reference type.
class Animal {
void sound() {
System.out.println("Animal makes a
sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class TestDispatch {
public static void main(String[] args) {
Animal a; // Reference of superclass
a = new Dog(); // Dog object
a.sound(); // Output: Dog barks
(decided at runtime)
a = new Cat(); // Cat object
a.sound(); // Output: Cat meows
(decided at runtime)
}
}
Abstract Class
● A class that you cannot create objects from directly.
● It can have abstract methods (methods without a body) and/or normal methods
(with a body).
● The subclass must provide the code (implementation) for the abstract methods
abstract class Animal {
abstract void sound(); // abstract method
- no body
void sleep() { // normal method
System.out.println("Animal is
sleeping");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
public class TestAbstract {
public static void main(String[] args) {
// Animal a = new Animal(); // ❌ Not
allowed
Dog d = new Dog();
d.sound(); // Dog barks
d.sleep(); // Animal is sleeping
}
}
Defining an Interface
● An interface is like a contract: it declares what methods a class must have,
but not how they work.
● All methods in an interface are public and abstract by default (no method
body).
● Variables in an interface are public, static, and final by default (constants).
interface Animal {
void sound(); // abstract method
void eat(); }
Implementing an Interface
● A class uses the keyword implements to agree to the interface’s “contract”.
● The class must provide code for all methods in the interface.
class Dog implements Animal {
public void sound() {
System.out.println("Dog
barks");
}
public void eat() {
System.out.println("Dog eats
bones");
}}
public class TestInterface {
public static void main(String[]
args) {
Dog d = new Dog();
d.sound();
d.eat();
}}
3. Extending Interfaces
● One interface can inherit from another using the extends keyword.
● The child interface gets all methods from the parent interface.
interface Animal {
void sound();
}
interface Pet extends Animal {
void play();
}
class Dog implements Pet {
public void sound() {
System.out.println("Dog barks");
}
public void play() {
System.out.println("Dog plays fetch");
}
}
public class TestExtendInterface {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.play();
}
}
extends with interfaces
● Used when one interface inherits from another
interface.
● The child interface gets all the abstract methods
from the parent interface(s).
● An interface can extend multiple interfaces
(supports multiple inheritance).
implements with interfaces
● Used when a class provides code for all methods
in an interface.
● A class can implement multiple interfaces.
● The class must override all abstract methods from
the interfaces.
interface A {
void methodA();}
interface B {
void methodB();}
class MyClass implements A, B {
public void methodA() {
System.out.println("Method A implemented"); }
public void methodB() {
System.out.println("Method B implemented"); }
}
Packages
● A package is like a folder that groups related Java classes,
interfaces, and sub-packages.
● Helps organize code and avoid name conflicts.
● Java has built-in packages (e.g., java.util, java.io) and
user-defined packages.
Creating a Package (Your Own Folder of Classes)
1. Make a folder → name it as your package name.
Example: mypack
2. Write your class inside that folder.
3. At the top of your Java file, write:
At the top of your Java file, write:
package mypack;
4.Compile it normally. The .class file will stay inside the mypack folder.
Example file: mypack/Hello.java
package mypack;
public class Hello {
public void greet() {
System.out.println("Hello from mypack!");
}
}
Implementing (Using) the Package
1.In another Java file outside the mypack folder, write:
import mypack.Hello;
2.Create an object and use it.
Example file: TestPackage.java
import mypack.Hello; // bring Hello into this file
public class TestPackage {
public static void main(String[] args) {
Hello obj = new Hello();
obj.greet();
}
}
Steps to Run
Compile the package class:
javac mypack/Hello.java
Compile the main program:
javac TestPackage.java
Run the program:
java TestPackage
Output:
Hello from mypack!
Creating → Make folder → write package folderName; at top → compile.
Implementing → Use import folderName.ClassName; → create object → run.
Implementing (Using) the Package
Example file: mypack/Hello.java
package mypack;
public class Hello {
public void greet() {
System.out.println("Hello from mypack!");
}
}

Unit 2-BCA- Classes, Inheritance & interface .pdf

  • 1.
    Unit 2: Classes,Inheritance, Packages & Interfaces(15) Classes: Class fundamentals; Methods; Naming conventions; Declaring objects; Access specifiers; Constructors; Command line arguments; Method Overloading; keywords: this, final; Static; abstract, finalize. Inheritance:Single; Multilevel inheritance; Method overriding-Dynamic method dispatch; Abstract classes, Usage of super. Interfaces:Defining an interface; Implementing interfaces; Extending interfaces. Packages:user defined packages; creating and implementing packages.
  • 2.
    Definition of Classand Object Class: A class in Java is a blueprint for creating objects. It contains fields (variables) and methods (functions) that define the behavior of the objects. class Student { int id; String name; } Object: An object is an instance of a class. It is created using the new keyword. Student s1 = new Student();
  • 3.
    2. Fields andMethods Fields are variables defined inside a class that hold data. Methods define actions or behavior of the class. class Student { int id; String name; void display() { System.out.println(id + " " + name); } }
  • 4.
    Object Instantiation Creating anobject involves: ○ Declaring a reference variable of the class. ○ Using the new keyword to allocate memory. Student s1 = new Student(); // Object created After instantiation, fields can be accessed and methods can be called using the dot (.) operator: s1.id = 101; s1.name = "Alice"; ● s1.display();
  • 5.
    4. Syntax andNaming Conventions ● Class Names: Should begin with an uppercase letter. Example: Student, Employee. ● Variable and Method Names: Should begin with a lowercase letter and use camelCase. Example: studentName, displayInfo. ● Use meaningful names to improve readability.
  • 6.
    Introduction to AccessSpecifiers Access specifiers define the accessibility (visibility) of classes, fields, constructors, and methods. The main access specifiers in Java are: Specifier Access Level Public Accessible from any class Private Accessible only within the same class Protected Accessible within the same package or subclass (default) Accessible only within the same package
  • 7.
    1. public ● Opento everyone. ● Can be accessed from anywhere in your program. public class A { public int x = 10; } You can access x from any other class.
  • 8.
    2. private ● Lockedinside the class. ● Can only be used within the same class. public class A { private int y = 20; public void show() { System.out.println(y); // ✅ allowed here } } You cannot use y from outside the class.
  • 9.
    3. protected ● Canbe used inside the class, inside the package, and by child classes (subclasses) even if in another package. public class A { protected int z = 30; } Subclass or same-package class can access z.
  • 10.
    4. Default (nokeyword) ● If you don’t write anything, it's accessible only in the same package. class A { int a = 40; // default access } Only other classes in the same package can access a.
  • 11.
    Feature Default Protected KeywordNo keyword used Uses protected keyword Same Class ✅ Accessible ✅ Accessible Same Package ✅ Accessible ✅ Accessible Subclass in Same Package ✅ Accessible ✅ Accessible Subclass in Different Package ❌ Not accessible ✅ Accessible Non-subclass in Different Package ❌ Not accessible ❌ Not accessible
  • 12.
    File: A.java (inpackage1) package package1; public class A { int x = 10; // default protected int y = 20; // protected }
  • 13.
    File: B.java (inpackage2, subclass of A) package package2; import package1.A; public class B extends A { public void show() { // System.out.println(x); // Error: default not accessible outside package System.out.println(y); // ✅ OK: protected accessible in subclass } }
  • 14.
    Constructors & Overloading Aconstructor is a special method that is automatically called when an object is created. It has the same name as the class and no return type (not even void). Types of Constructors Default Constructor Parameterized Constructor
  • 15.
    Default Constructor ● Createdby the compiler if no constructor is defined. ● Takes no arguments and sets default values. class Student { int id; String name; Student() { // Default constructor id = 0; name = "Not Assigned"; } void display() { System.out.println(id + " " + name); }}
  • 16.
    Parameterized Constructor ● Takesparameters to assign values when object is created. class Student { int id; String name; Student(int i, String n) { // Parameterized constructor id = i; name = n; } void display() { System.out.println(id + " " + name); }}
  • 17.
    3. Constructor Overloading ●Multiple constructors in a class with different parameter lists. ● Helps in creating objects in multiple ways.
  • 18.
    class Student { intid; String name; // Default constructor Student() { id = 0; name = "NA";} // Parameterized constructor Student(int i, String n) { id = i; name = n; } void display() { System.out.println(id + " " + name); }}
  • 19.
    4. Method Overloading ●Same method name with different parameters (type or number). ● Compile-time polymorphism. class Calculator { int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } }
  • 20.
    Constructor vs Method FeatureConstructor Method Name Same as class name Any name Return Type No return type Must have a return type Called When Automatically during object creation Called manually by object Purpose Initialize object Perform action
  • 21.
    class Book { Stringtitle; int pages; // Constructor Book(String t, int p) { title = t; pages = p; } // Overloaded method void display() { System.out.println(title + " has " + pages + " pages."); } void display(String author) { System.out.println(title + " by " + author); } } public class Main { public static void main(String[] args) { Book b1 = new Book("Java Basics", 250); b1.display(); b1.display("John"); } }
  • 22.
    Access Specifiers inJava Access specifiers control the visibility of classes, methods, and variables. Specifier Accessible Within Class Within Package Outside Package (Subclass) Outside Package public ✔ ✔ ✔ ✔ private ✔ ✘ ✘ ✘ protected ✔ ✔ ✔ ✘
  • 23.
    public class Demo{ public int a; // Accessible everywhere private int b; // Accessible only inside class protected int c; // Accessible in subclass or same package int d; // default - package only }
  • 24.
    Command Line Argumentsin Java Command line arguments are values passed to a Java program when it is run from the command line. ● They are passed during program execution. ● They are stored in the String[] args array in the main() method. ● Useful when you want to provide input without using Scanner or GUI.
  • 25.
    Example Program public classCommandLineExample { public static void main(String[] args) { System.out.println("Number of arguments: " + args.length); for (int i = 0; i < args.length; i++) { System.out.println("Argument " + i + ": " + args[i]); } } }
  • 26.
    javac CommandLineExample.java java CommandLineExampleHello World 123 OUTPUT: Number of arguments: 3 Argument 0: Hello Argument 1: World Argument 2: 123
  • 27.
    Method Overloading inJava Method Overloading means defining multiple methods in the same class with the same name but different parameters (type, number, or order of parameters). ● To perform different tasks using the same method name. ● Improves code readability and reusability. To overload a method: ● Method name must be the same. ● Parameters must be different by: ○ Number of parameters ○ Data types of parameters ○ Order of parameters Return type does not matter in overloading.
  • 28.
    public class Calculator{ // Method with one int parameter void add(int a) { System.out.println("Sum: " + (a + 10)); } // Method with two int parameters void add(int a, int b) { System.out.println("Sum: " + (a + b)); } // Method with two double parameters void add(double a, double b) { System.out.println("Sum: " + (a + b)); } public static void main(String[] args) { Calculator calc = new Calculator(); calc.add(5); // calls method with one int calc.add(5, 10); // calls method with two ints calc.add(2.5, 3.5); // calls method with two doubles } } Output: Sum: 15 Sum: 15 Sum: 6.0
  • 29.
    Benefits of MethodOverloading ● Cleaner code ● Same method name for similar operations ● Easier to maintain
  • 30.
    keywords: this, final;Static; abstract, finalize.
  • 31.
    2. this Keyword ●Refers to current class object. ● Used when local variable name is same as instance variable. Example: class Student { int id; Student(int id) { this.id = id; // this refers to instance variable }}
  • 32.
    Without this, theline: id = id; would assign the parameter id to itself — which does nothing. With this: this.id = id; …it means: ● this.id → instance variable ● id → constructor parameter So the instance variable gets the value passed to the constructor. this.id = id; means: "Assign the constructor’s id value to the object’s id variable."
  • 33.
    final Keyword ● Usedto prevent changes. Usage Meaning final variable cannot be changed final method cannot be overridden final class cannot be inherited
  • 34.
    final int x= 10; // x = 20; Error final class A { } // class B extends A {} Error
  • 35.
    b. Static Method ●Can be called without creating object. ● Can access only static data. class MyClass { static void sayHello() { System.out.println("Hello from static method!"); }} public class Test { public static void main(String[] args) { MyClass.sayHello(); // No need to create an object }}
  • 36.
    4. final Keyword ●Used to make variable constant, method non-overridable, or class non-inheritable. a. Final Variable final int x = 10; // x = 20; // Error: Cannot change value b. Final Method class A { final void show() { System.out.println("Final method"); } } c. Final Class final class Vehicle { } // class Car extends Vehicle {} // Error: Cannot inherit final class
  • 37.
    3. static Keyword ●Used with variables, methods, and blocks. ● Shared by all objects of the class. a. Static Variable ● One copy shared by all objects.
  • 38.
    class Counter { staticint count = 0; Counter() { count++; System.out.println(count); }} public class Test { public static void main(String[] args) { Counter c1 = new Counter(); // count becomes 1 Counter c2 = new Counter(); // count becomes 2 Counter c3 = new Counter(); // count becomes 3 } }
  • 39.
    5. finalize() Method ●Called by Garbage Collector before object is destroyed. ● Used for cleanup activities.(It is called by the Garbage Collector (GC) before an object is destroyed, to perform cleanup tasks (like closing files, releasing resources, etc.).) class Example { protected void finalize() { System.out.println("Object is destroyed"); } }
  • 40.
    abstract in Java Anabstract is a keyword used for abstract classes and abstract methods. ● Abstract class: ○ Cannot be directly instantiated (you can’t create an object from it). ○ Can contain abstract methods (methods without a body) and normal methods (methods with code). ● Abstract method: ○ Declared without a body — only the method signature is given. ○ Must be implemented by the subclass. Why use it? To create a blueprint for other classes — useful when you want all subclasses to follow a certain structure.
  • 41.
    abstract class Animal{ abstract void sound(); // abstract method (no body) void sleep() { // normal method System.out.println("Sleeping..."); }} class Dog extends Animal { void sound() { System.out.println("Bark!"); }} public class Main { public static void main(String[] args) { // Animal a = new Animal(); // Cannot create object of abstract class Animal myDog = new Dog(); myDog.sound(); // Output: Bark! myDog.sleep(); // Output: Sleeping...
  • 42.
    Inheritance in Java Definition: Inheritancelets one class (child/subclass) reuse the fields and methods of another class (parent/superclass). We use the extends keyword. a) Single Inheritance One subclass inherits from one superclass.
  • 43.
    class Animal { voideat() { System.out.println("Eating..."); }} class Dog extends Animal { void bark() { System.out.println("Barking..."); }} public class Main { public static void main(String[] args) { Dog d = new Dog(); d.eat(); // From Animal d.bark(); // From Dog }}
  • 44.
    b) Multilevel Inheritance Achain of inheritance — one class inherits from another, which inherits from another. class Animal { void eat() { System.out.println("Eating..."); } } class Dog extends Animal { void bark() { System.out.println("Barking..."); } } class Puppy extends Dog { void weep() { System.out.println("Weeping..."); } } public class Main { public static void main(String[] args) { Puppy p = new Puppy(); p.eat(); // From Animal p.bark(); // From Dog p.weep(); // From Puppy } } OUTPUT Eating... Barking... Weeping...
  • 45.
    Method Overriding &Dynamic Method Dispatch ● Method Overriding: A subclass provides its own version of a method that already exists in the superclass. ● Dynamic Method Dispatch: The method that gets called is decided at runtime based on the object type, not the reference type.
  • 46.
    class Animal { voidsound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { void sound() { System.out.println("Cat meows"); } } public class TestDispatch { public static void main(String[] args) { Animal a; // Reference of superclass a = new Dog(); // Dog object a.sound(); // Output: Dog barks (decided at runtime) a = new Cat(); // Cat object a.sound(); // Output: Cat meows (decided at runtime) } }
  • 47.
    Abstract Class ● Aclass that you cannot create objects from directly. ● It can have abstract methods (methods without a body) and/or normal methods (with a body). ● The subclass must provide the code (implementation) for the abstract methods
  • 48.
    abstract class Animal{ abstract void sound(); // abstract method - no body void sleep() { // normal method System.out.println("Animal is sleeping"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class TestAbstract { public static void main(String[] args) { // Animal a = new Animal(); // ❌ Not allowed Dog d = new Dog(); d.sound(); // Dog barks d.sleep(); // Animal is sleeping } }
  • 49.
    Defining an Interface ●An interface is like a contract: it declares what methods a class must have, but not how they work. ● All methods in an interface are public and abstract by default (no method body). ● Variables in an interface are public, static, and final by default (constants). interface Animal { void sound(); // abstract method void eat(); }
  • 50.
    Implementing an Interface ●A class uses the keyword implements to agree to the interface’s “contract”. ● The class must provide code for all methods in the interface. class Dog implements Animal { public void sound() { System.out.println("Dog barks"); } public void eat() { System.out.println("Dog eats bones"); }} public class TestInterface { public static void main(String[] args) { Dog d = new Dog(); d.sound(); d.eat(); }}
  • 51.
    3. Extending Interfaces ●One interface can inherit from another using the extends keyword. ● The child interface gets all methods from the parent interface. interface Animal { void sound(); } interface Pet extends Animal { void play(); } class Dog implements Pet { public void sound() { System.out.println("Dog barks"); } public void play() { System.out.println("Dog plays fetch"); } } public class TestExtendInterface { public static void main(String[] args) { Dog d = new Dog(); d.sound(); d.play(); } }
  • 52.
    extends with interfaces ●Used when one interface inherits from another interface. ● The child interface gets all the abstract methods from the parent interface(s). ● An interface can extend multiple interfaces (supports multiple inheritance). implements with interfaces ● Used when a class provides code for all methods in an interface. ● A class can implement multiple interfaces. ● The class must override all abstract methods from the interfaces.
  • 53.
    interface A { voidmethodA();} interface B { void methodB();} class MyClass implements A, B { public void methodA() { System.out.println("Method A implemented"); } public void methodB() { System.out.println("Method B implemented"); } }
  • 54.
    Packages ● A packageis like a folder that groups related Java classes, interfaces, and sub-packages. ● Helps organize code and avoid name conflicts. ● Java has built-in packages (e.g., java.util, java.io) and user-defined packages.
  • 55.
    Creating a Package(Your Own Folder of Classes) 1. Make a folder → name it as your package name. Example: mypack 2. Write your class inside that folder. 3. At the top of your Java file, write: At the top of your Java file, write: package mypack; 4.Compile it normally. The .class file will stay inside the mypack folder.
  • 56.
    Example file: mypack/Hello.java packagemypack; public class Hello { public void greet() { System.out.println("Hello from mypack!"); } }
  • 57.
    Implementing (Using) thePackage 1.In another Java file outside the mypack folder, write: import mypack.Hello; 2.Create an object and use it.
  • 58.
    Example file: TestPackage.java importmypack.Hello; // bring Hello into this file public class TestPackage { public static void main(String[] args) { Hello obj = new Hello(); obj.greet(); } }
  • 59.
    Steps to Run Compilethe package class: javac mypack/Hello.java Compile the main program: javac TestPackage.java Run the program: java TestPackage Output: Hello from mypack! Creating → Make folder → write package folderName; at top → compile. Implementing → Use import folderName.ClassName; → create object → run.
  • 60.
    Implementing (Using) thePackage Example file: mypack/Hello.java package mypack; public class Hello { public void greet() { System.out.println("Hello from mypack!"); } }