0% found this document useful (0 votes)
4 views61 pages

Projava Ebook 1

Unit 1 covers key features of Java, including its platform independence, object-oriented nature, and automatic memory management. It contrasts Java with C++, detailing differences in syntax, memory management, and inheritance. The unit also explains Java program structure, JVM functionality, data types, operators, control structures, and includes knowledge checks and activities for student assessment.

Uploaded by

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

Projava Ebook 1

Unit 1 covers key features of Java, including its platform independence, object-oriented nature, and automatic memory management. It contrasts Java with C++, detailing differences in syntax, memory management, and inheritance. The unit also explains Java program structure, JVM functionality, data types, operators, control structures, and includes knowledge checks and activities for student assessment.

Uploaded by

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

Unit 1

Learning Outcomes:
 Students will be able to iden fy and describe the key features of Java, such as
its pla orm independence, object-oriented nature, and automa c memory
management.
 Students will be able to differen ate between Java and C++ by comparing their
syntax, memory management, and pla orm dependence.
 Students will be able to demonstrate the ability to construct Java program
structures, including class declara ons, main methods, and the use of packages
and comments.
 Students will be able to explain the role and func onality of the JVM, including
bytecode execu on and pla orm independence.
 Students will be able to apply various control structures (like loops and
condi onals) and effec vely use arrays in Java programming to solve problems.

Structure:
1.1 Java features
1.2 How Java differs from C++
1.3 Java Program Structure
1.4 Java Tokens
1.5 Java virtual machine
1.6 Constants, variables and data types
1.7 Operators & expressions
1.8 Control structures
1.9 Arrays
 Knowledge Check 1
 Outcome-Based Ac vity 1
1.10 class & object
1.11 garbage collec on
1.12 finalize() method
1.13 Inheritance
1.14 method overriding
1.15 Abstract class
1.16 Interfaces, Extending Interfaces & Accessing Interface variables.
 Knowledge Check 2
 Outcome-Based Ac vity 2
1.17 Summary
1.18 Keywords
1.19 Self-Assessment Ques ons
1.20 References / Reference Reading

1.1Java Features:
Portability:
The WORA principle states that Java code is turned into bytecode, an intermediate
form that may run on any device that has a Java Virtual Machine (JVM).
Object-Oriented:
 Java is fundamentally object-oriented, promo ng the use of classes and objects.
 Encapsula on, inheritance, and polymorphism are integral concepts in Java.
Pla orm Independence:
 Java applica ons can run on any pla orm with a compa ble JVM.
 Reduces dependency on the underlying hardware and opera ng system.
Automa c Memory Management:
 Garbage Collec on automa cally manages memory, freeing developers from
manual memory alloca on and dealloca on.
Security:
 Built-in security features to create secure applica ons.
 The bytecode verifier ensures that code running on the JVM is safe.
Mul threading:
 Java supports concurrent execu on with built-in support for mul threading.
 Allows the crea on of responsive and efficient applica ons.

1.2 How Java Differs from C++:


Pla orm Independence:
Java is pla orm-independent due to the bytecode and JVM, while C++ code needs
to be compiled separately for each pla orm.
Memory Management:
Because Java offers automa c garbage collec on, it does not require the tedious
manual memory management that C++ does.
Syntax and Complexity:
Java has a simpler syntax compared to C++, making it more readable and easier to
learn.
Pointers:
Java does not support pointers, reducing the risk of memory-related bugs, whereas
C++ allows explicit use of pointers.
Mul ple Inheritance:
C++ supports mul ple inheritance, while Java achieves a similar effect through
interfaces and avoids the complexi es associated with mul ple inheritance.

1.3 Java Program Structure:

1. Class Declara on:


 Java programs are structured around classes.
 The `class` keyword is used to declare a class.
2. Main Method:
A Java program's entry point is the `main` method, which has the following
signature: `public sta c void main(String[] args)}.
3. Packages:
 Packages organize classes into namespaces.
 The `package` statement is used to define a package.
4. Import Statements:
 `import` statements are used to include classes from other packages.
 Improves code readability and avoids naming conflicts.
5. Comments:
 {//} is the beginning of a single line of comment, and {/} is the end of a mul -
line comment.
 Comments enhance code readability and provide documenta on.

1.4 Java Tokens:


In Java, a token is the smallest unit of a program that is meaningful to the compiler.
These tokens are the building blocks of a Java program and can be categorized into
the following types:

Keywords

Special Indentifiers
Symbols

Modifiers Literals
Tokens
in Java

White
Operators
Spaces

Comments Separators

Keywords:
 Reserved words with predefined meanings.
 Examples: `class`, `public`, `sta c`, `void`, etc.
Iden fiers:
 Names given to variables, methods, classes, etc., by the programmer.
 Must start with a le er, underscore (_), or dollar sign ($) and can be followed by
le ers, digits, underscores, or dollar signs.
Literals:
 Represent constant values.
 Examples: Numeric literals (e.g., `12`, `3.14`), character literals (`'A'`), string
literals (`"Hello"`), boolean literals (`true` or `false`).
Operators:
 Symbols that perform opera ons on variables and values.
 Examples: Arithme c operators (`+`, `-`, ``, `/`), rela onal operators (`<`, `>`, `==`,
`!=`), logical operators (`&&`, `||`).
Separators:
 Characters used to separate statements and define the structure of the program.
 Examples: Semicolon (`;`), comma (`,`), parentheses (`()`), curly braces (`{}`),
square brackets (`[]`).
Comments:
 Not treated as a part of the program but are useful for documenta on.
 Mul -line comments are encapsulated between {/} and {/}, while single-line
comments begin with {//}.
White Spaces:
 Spaces, tabs, and line breaks that separate tokens.
 Ignored by the compiler but enhance code readability.
Modifiers:
 Keywords that define the scope and behavior of variables, methods, and classes.
 Examples: `public`, `private`, `sta c`, `final`.
Special Symbols:
 Symbols with special meanings in Java.
 Examples: `@` (used in annota ons), `::` (method reference), `...` (varargs).

1.5 Java virtual machine


Let's examine the internal structure of the JVM. It includes the memory area,
execu on engine, classloader, and so forth.

1. Defini on: An abstract compu ng machine, or JVM, offers a run me


environment for Java bytecode execu on.It acts as a bridge between Java programs
and the opera ng system and underlying hardware.
2. Important Elements:
 Class Loader: This program is in charge of loading Java classes into RAM.
- There are three kinds of loaders: Applica on, Extension, and Bootstrap.
 Bytecode Verifier: Verifies that the bytecode complies with Java's safety
requirements and is legi mate.
- Aids in preven ng security flaws.
 Interpreter: - Line by line interprets and runs Java bytecode.
- Offers pla orm independence through dynamic bytecode interpreta on.
 Just-In-Time (JIT) Compiler: - Converts bytecode into the host system's na ve
machine code.
- Increases performance by using na ve code execu on as opposed to
interpreta on.
 Areas of Run me Data:
- Method Domain:
- Preserves class-level structures, including method and field data.
 Heap: Objects and their instance variables are stored in this memory region.
This is where garbage collec on happens.
3. Execu on Process:
 The Java Compiler transforms Java source code into bytecode (.class files).
 Any device with a compa ble Java virtual machine (JVM) can run the
bytecode, regardless of the pla orm.
 The JVM loads the program, checks the bytecode, and runs the classes.
4. Pla orm Independence:
 JVM's ability to execute bytecode on any pla orm with a JVM
implementa on.
 Eliminates the need to recompile code for different pla orms.
5. Memory Management:
 Automa c Garbage Collec on in the heap area.
 Allocates and deallocates memory dynamically, reducing the risk of memory
leaks.
6. Security Features:
 Bytecode verifica on prevents execu on of malicious code.
 Security Manager allows fine-grained control over resources.
7. JVM Implementa ons:
 Various vendors provide JVM implementa ons (e.g., Oracle HotSpot, OpenJ9,
GraalVM).
 Each implementa on adheres to the Java Virtual Machine Specifica on.
8. Performance Op miza on:
 JIT compila on enhances performance by transla ng bytecode to na ve
code at run me.
 Adap ve op miza on techniques improve execu on efficiency.
9. Debugging and Profiling:
 JVM provides tools for debugging (e.g., Java Debugger - JDWP) and profiling
(e.g., VisualVM).
 Facilitates monitoring and analysis of Java applica ons.

1.6 Constants, Variables, and Data Types:


1. Constants:
 Defini on: Constants are iden fiers whose values don't change while a
program is running.
 Declara on:
- Declared using the `final` keyword.
- Example: `final double PI = 3.14159;`
2. Variables:
 Defini on: Variables are named memory loca ons used to store data that can
be changed during program execu on.
 Declara on:
- Syntax: `data_type variable_name;`
- Example: `int age;`
 Ini aliza on:
- The process of ini alizing a variable involves giving it a star ng value.
- Example: `age = 25;`
 Types:
- Local Variables:
- Declared within a method or block and have limited scope.
- Instance Variables:
Belong to an instance of a class and are declared within the class but outside
any method.
- Class (Sta c) Variables:
Shared among all instances of a class and declared using the `sta c`
keyword.
3. Data Types:
 Primi ve Data Types:
- Numeric Types:
o `byte`: 8-bit signed integer.
o `short`: 16-bit signed integer.
o `int`: 32-bit signed integer.
o `long`: 64-bit signed integer.
o `float`: 32-bit floa ng-point number.
o `double`: 64-bit floa ng-point number.
- Character Type:
o `char`: 16-bit Unicode character.
- Boolean Type:
o `boolean`: Represents true or false values.
 Non-Primi ve Data Types:
- Arrays:
- Collec ons of elements of the same type.
- Declared using `data_type[] array_name;`.
- Example: `int[] numbers = {1, 2, 3, 4};`
- Strings:
- Sequences of characters.
- `String` is a class in Java.
- Example: `String gree ng = "Hello";`
4. Type Cas ng:
 Implicit Cas ng:
- Conversion of a smaller data type to a larger data type automa cally.
- Example: `int intValue = 10; long longValue = intValue;`
 Explicit Cas ng:
- Manual conversion of a larger data type to a smaller data type.
- Example: `double doubleValue = 10.5; int intValue = (int) doubleValue;`
1.7 Operators & Expressions:
1. Operators:
 Defini on:
- Operators are symbols used to perform opera ons on variables and values in
expressions.
 Types:
 Arithme c Operators:
- Perform basic mathema cal opera ons.
- Examples: `+` (addi on), `-` (subtrac on), `` (mul plica on), `/` (division), `%`
(modulo).
 Rela onal Operators:
- Compare two values and return a boolean result.
- Examples: `==` (equal to), `!=` (not equal to), `<` (less than), `>` (greater than),
`<=` (less than or equal to), `>=` (greater than or equal to).
 Logical Operators:
- Combine boolean expressions.
- Examples: `&&` (logical AND), `||` (logical OR), `!` (logical NOT).
 Assignment Operators:
- Assign values to variables.
- Examples: `=` (assignment), `+=` (addi on assignment), `-=`, `=`, `/=`.
 - Increment/Decrement Operators:
- Increase or decrease the value of a variable by 1.
- Examples: `++` (increment), `--` (decrement).
 Bitwise Operators:
- Perform opera ons on individual bits of binary representa ons.
- Examples: `&` (bitwise AND), `|` (bitwise OR), `^` (bitwise XOR), `~` (bitwise
NOT).
 - Condi onal (Ternary) Operator:
- A shorthand for an if-else statement.
- Example: `result = (a > b) ? a : b;`
2. Expressions:
 Defini on:
- A set of variables, constants, and operators that together produce a value is
called an expression.
Examples:
- Arithme c Expression: `int result = x + y;`
- Rela onal Expression: `boolean isEqual = (a == b);`
- Logical Expression: `boolean isValid = (age > 18) && (gender == 'M');`
- Assignment Expression: `total += quan ty price;`
3. Precedence and Associa vity:
 Precedence:
- Determines the order of evalua on when mul ple operators are present.
- Example: `` has higher precedence than `+`, so `2 + 3 4` is evaluated as `2 + (3
4)`.
 Associa vity:
- Determines the order of evalua on for operators with the same precedence.
- Example: Addi on `+` is le -associa ve, so `a + b + c` is evaluated as `(a + b) +
c`.
4. Type Conversion (Cas ng):
 Implicit Conversion:
- Automa c conversion of lower data types to higher data types.
- Example: `int intValue = 5; double doubleValue = intValue;`
 Explicit Conversion:
- Manual conversion of higher data types to lower data types.
- Example: `double doubleValue = 5.5; int intValue = (int) doubleValue;`

1.8Control structures
 Condi onal Statements:
1 `if` Statement:
A block of code can only be executed by the `if` statement if a par cular condi on
is met.

if (condi on) { // Code to be run in the event that the condi on is sa sfied }

Using int x = 10 as an example, if (x > 5) { System.out.println("x is greater than 5");


}

2 `if-else` Statement:
If the condi on is true, you can run one block of code using the `if-else` statement;
if it is false, you can run an other chunk of code.

if (condi on) { // Code to be run in the event that the condi on is sa sfied } If the
condi on is false, then else { // Code to be executed }
An illustra on would be as follows: int y = 3; if (y % 2 == 0) { System.out.println("y
is even"); } else { System.out.println("y is odd");

3 `switch` Statement:
The `switch` statement is used to select one of many code blocks to be executed.

switch (variable) {
case value1:
// Code to be executed if variable equals value1
break;
case value2:
// Code to be executed if variable equals value2
break;
// addi onal cases...
default:
// Code to be executed if none of the cases match
}

Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// addi onal cases...
default:
System.out.println("Invalid day");
}

 Looping Statements:
1 `for` Loop:
The `for` loop is used to iterate a block of code a specific number of mes.

for (ini aliza on; condi on; update) {


// Code to be executed in each itera on
}

Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Itera on " + i);
}

2 `while` Loop:
The `while` loop con nues to execute a block of code as long as the specified
condi on is true.
while (condi on) {
// Code to be executed as long as the condi on is true
}

Example:
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}

3 `do-while` Loop:
The `do-while` loop is similar to the `while` loop, but it ensures that the code block
is executed at least once, even if the condi on is ini ally false.

do {
// Code to be executed at least once
} while (condi on);

Example:
int num = 1;
do {
System.out.println("Number: " + num);
num++;
} while (num <= 3);

1.9Arrays
1. Arrays in Java:
In Java, an array is a form of data structure that lets you have several values of the
same kind stored under one variable name. Data collec ons are easier to maintain
and work with when arrays are used.
2. Declara on and Ini aliza on:
 Declara on:
The data type of each element that the array will contain must be specified before
the array name and square brackets {[]} are used to declare the array.
dataType[] arrayName;

Example:
int[] numbers;

 Ini aliza on:


You can ini alize an array at the me of declara on or later using the `new`
keyword.

Inline Ini aliza on:


dataType[] arrayName = {value1, value2, value3, ...};

Example:
int[] numbers = {1, 2, 3, 4, 5};
 Using `new` Keyword:
dataType[] arrayName = new dataType[size];

Example:
int[] numbers = new int[5];

3. Accessing Array Elements:


Array elements are accessed using their index, star ng from 0 for the first element.

dataType element = arrayName[index];

Example:
int thirdElement = numbers[2]; // Accessing the third element (index 2) of the
'numbers' array.

4. Array Length:
The length of an array, indica ng the number of elements it can hold, can be
obtained using the `length` property.

int arrayLength = arrayName.length;

Example:
int length = numbers.length; // Returns the length of the 'numbers' array.
5. Itera ng Through an Array:
 `for` Loop:
for (int i = 0; i < arrayName.length; i++) {
// Access and process array elements using arrayName[i]
}

Example:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

 Enhanced `for` Loop (for-each):


for (dataType element : arrayName) {
// Process each element directly
}

Example:
for (int num : numbers) {
System.out.println(num);
}

6. Mul dimensional Arrays:


Java supports mul dimensional arrays, such as 2D arrays.

Declara on:
dataType[][] arrayName;

Example:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

Access elements in a 2D array using two indices: `matrix[rowIndex][columnIndex]`.

 Knowledge Check 1
Fill in the Blanks
1. Java is known for its __________ programming paradigm. (Object-
Oriented/Procedural)
2. Unlike C++, Java does not support explicit __________. (Memory
Management/Pointers)
3. The _________method is a mandatory entry point for the execu on of a Java
program. (Main/Start)
4. Iden fiers in Java must start with a ______ or underscore. (Le er/Number)
5. The JVM interprets Java source code and translates it into __________ for
execu on on the host system. (Bytecode/Machine Code)

 Outcomes-Based Ac vity 1
Implement a Java program that simulates a library system. U lize object-
oriented principles to create classes for books, library users, and transac ons.
Showcase pla orm independence by running the program on different
opera ng systems.
1.10 Class & Object
1. Classes in Java:
 Defini on:
In Java, a class is an object crea on blueprint or template. It combines behavior
and data into one cohesive unit. The building blocks of object-oriented
programming are classes.
 Syntax:
// Class Declara on
public class ClassName {
// Fields (a ributes/variables)
dataType fieldName;

// Methods (func ons)


returnType methodName(parameters) {
// Method body
}
}

Example:
public class Car {
// Fields
String make;
String model;
int year;
// Methods
void startEngine() {
System.out.println("Engine started!");
}
}

2. Objects in Java:
 Defini on:
An instance of a class is called an object. It is constructed from a class defini on and
represents an actual thing. The class defines the state and behavior of an
object.Object Crea on:
// Syntax
ClassName objectName = new ClassName();

Example:
Car myCar = new Car();

 Accessing Fields and Methods:


// Accessing Fields
objectName.fieldName;

// Invoking Methods
objectName.methodName(parameters);

Example:
// Accessing Fields
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;

// Invoking Methods
myCar.startEngine();

3. Constructors:
 Defini on:
When an object is formed, a class's constructor—a unique method—is called. It sets
the object's state to ini al.
 Default and Parameterized Constructors:
// Default Constructor
public ClassName() {
// Ini aliza on code
}

// Parameterized Constructor
public ClassName(parameterType param1, parameterType param2, ...) {
// Ini aliza on code using parameters
}

Example:
public class Student {
String name;
int age;

// Default Constructor
public Student() {
name = "Unknown";
age = 0;
}

// Parameterized Constructor
public Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
}

4. Encapsula on:
 Defini on:
Combining data (fields) and methods that work with the data into a single unit
(class) is known as encapsula on. It aids in data concealing and safeguards the
object's integrity.
• Modifiers of Access:
- {public}: Reachable from any loca on.
- {private}: Only available inside the class.
- {protected}: Available only within this class and any of its child classes.
- (default): Available inside the same bundle.

Example:
public class BankAccount {
private double balance; // private field

// public method for accessing private field


public double getBalance() {
return balance;
}
}

Program
// Define the class
class Car {
// Fields
String make;
String model;
int year;

// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}

// Method to display car informa on


public void displayInfo() {
System.out.println("Car Informa on:");
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}

// Main class
public class CarExample {
public sta c void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Toyota", "Camry", 2022);

// Access fields and invoke methods


myCar.displayInfo();
}
}

In this program:
1. The `Car` class is defined with fields (`make`, `model`, `year`), a constructor, and
a method (`displayInfo`) to display car informa on.
2. The `CarExample` class is the main class that contains the `main` method.
3. An object `myCar` of the `Car` class is created in the `main` method.
4. The fields of the `myCar` object are set using the constructor.
5. The `displayInfo` method is called to print the car informa on to the console.

This simple program illustrates the basic concepts of classes and objects in Java. The
`Car` class serves as a blueprint for crea ng car objects, and the `CarExample` class
demonstrates the crea on and usage of an object of the `Car` class.

1.11 Garbage collec on


1. Garbage Collec on in Java:
 Defini on:
Java's garbage collec on procedure finds and recovers memory that has been
taken by things that are no longer in use automa cally. It stops memory leaks
and aids in effec ve memory management.

 How Java Manages Memory:


Java manages memory with an automated garbage collector. Finding and
elimina ng items that the so ware no longer references or can reach is the main
concept.
Object Lifecycle:
- Crea on: Objects are created using the `new` keyword.
- Reference: Objects are referenced by variables.
- Dereference: When an object is no longer needed, its reference is set to `null`.
- Eligibility for Garbage Collec on: Objects without references become eligible
for garbage collec on.

2. Garbage Collec on Process:


 Mark and Sweep Algorithm:
- Mark Phase: Iden fies and marks objects that are reachable.
- Sweep Phase: Removes unreferenced objects.
 Memory Areas in Java Heap:
- Young Genera on: Newly created objects reside here.
- Old Genera on (Tenured Genera on): Objects that survive mul ple garbage
collec on cycles are moved here.

3. `finalize()` Method:
 Defini on:
The `finalize()` method is part of the `Object` class and is called by the garbage
collector before an object is reclaimed.

 Syntax:
protected void finalize() throws Throwable {
// Cleanup code before object is garbage collected
}

 Example:
public class MyClass {
// Class members...
protected void finalize() throws Throwable {
// Cleanup code
super.finalize();
}
}

4. `System.gc()` and `Run me.getRun me().gc()`:


 Defini on:
These methods can be used to suggest garbage collec on, but it's not guaranteed
that it will be immediately executed.
 Example:
System.gc(); // Suggests garbage collec on
Run me.getRun me().gc(); // Another way to suggest garbage collec on

5. Memory Management Best Prac ces:


 Nullify References:
Set object references to `null` when they are no longer needed.

 Limited Use of `finalize()`:


Avoid heavy opera ons in the `finalize()` method as it can delay the garbage
collec on process.
 Monitor Memory Usage:
Use tools like Java VisualVM to monitor memory usage and iden fy poten al
memory leaks.

6. Benefits of Garbage Collec on:


- Simplifies memory management by automa ng memory dealloca on.
- Reduces the chances of memory leaks and dangling references.
- Enhances developer produc vity by minimizing manual memory management.

Program

class MyClass {
// Class members...

// Constructor
public MyClass() {
System.out.println("Object created");
}

// Finalize method
protected void finalize() throws Throwable {
System.out.println("Object is being garbage collected");
// Cleanup code (if needed)
super.finalize();
}
}

public class GarbageCollec onExample {


public sta c void main(String[] args) {
// Crea ng an object
MyClass obj = new MyClass();

// Sugges ng garbage collec on


System.gc();

// Crea ng more objects to increase the chance of garbage collec on


for (int i = 0; i < 5; i++) {
new MyClass();
}

// Le ng some me pass to allow the garbage collector to work


try {
Thread.sleep(1000);
} catch (InterruptedExcep on e) {
e.printStackTrace();
}

System.out.println("End of the program");


}
}
In this program:
1. The `MyClass` class has a constructor, and it overrides the `finalize()` method for
cleanup before garbage collec on.
2. The `GarbageCollec onExample` class creates an instance of `MyClass`, suggests
garbage collec on using `System.gc()`, and creates addi onal objects to increase
the likelihood of garbage collec on.
3. The program then waits for some me to allow the garbage collector to perform
its task.

Please note that while using `System.gc()` suggests garbage collec on, the actual
execu on of garbage collec on is managed by the Java Virtual Machine (JVM), and
there's no guarantee that it will happen immediately. The `finalize()` method is
called before an object is garbage collected, and it can be used for any necessary
cleanup opera ons.

1.12 Inheritance
1. Inheritance in Java:
 Defini on:
A key idea in object-oriented programming is inheritance, which permits a class
(subclass or derived class) to take on characteris cs and traits from another class
(superclass or base class). It creates a "is-a" link between classes and encourages
code reuse.
 Syntax:
// Superclass (Base Class)
class Superclass {
// Fields and methods of the superclass
}

// Subclass (Derived Class)


class Subclass extends Superclass {
// Addi onal fields and methods of the subclass
}

2. Example of Inheritance in Java:


Let's consider an example involving a superclass `Vehicle` and a subclass `Car`:
 Superclass (Vehicle):
// Superclass
class Vehicle {
// Fields
String brand;
int year;

// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}

// Method
public void displayInfo() {
System.out.println("Vehicle Informa on:");
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}

 Subclass (Car):
// Subclass
class Car extends Vehicle {
// Addi onal fields
String model;

// Constructor
public Car(String brand, String model, int year) {
// Call the superclass constructor using 'super'
super(brand, year);
this.model = model;
}

// Addi onal method


public void drive() {
System.out.println("The car is now driving.");
}
}

 Using Inherited Classes:


// Main class
public class InheritanceExample {
public sta c void main(String[] args) {
// Create an object of the subclass (Car)
Car myCar = new Car("Toyota", "Camry", 2022);

// Access fields and methods from both superclass and subclass


myCar.displayInfo(); // Access method from superclass
myCar.drive(); // Access method from subclass
}
}

In this example:
- The `Vehicle` class is the superclass with fields and a method to display vehicle
informa on.
- The `Car` class is the subclass that extends `Vehicle`. It has addi onal fields and a
method.
- The `InheritanceExample` class demonstrates the crea on of a `Car` object and
the use of inherited methods from both the superclass and the subclass.
The Java inheritance link between the `Car` and `Vehicle` classes is demonstrated
by this program. In addi on to inheri ng fields and methods from the
superclass, the subclass is also allowed to have its own fields and methods.

1. Single Inheritance:
 Defini on:
A class that inherits from only one superclass is said to have single inheritance.
 Syntax:
// Superclass
class Superclass {
// Fields and methods of the superclass
}

// Subclass inheri ng from a single superclass


class Subclass extends Superclass {
// Addi onal fields and methods of the subclass
}

 Example:
// Single Inheritance Example
class Animal {
void eat() {
System.out.println("Animal is ea ng");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

public class SingleInheritanceExample {


public sta c void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog
}
}
2. Mul ple Inheritance (Through Interfaces):
 Defini on:
Java uses interfaces to support mul ple inheritance. Mul ple interfaces can be
implemented by a class.
 Syntax:
// Interface 1
interface Interface1 {
// Methods of Interface1
}

// Interface 2
interface Interface2 {
// Methods of Interface2
}

// Class implemen ng mul ple interfaces


class MyClass implements Interface1, Interface2 {
// Class members
}

 Example:
// Mul ple Inheritance Example through Interfaces
interface Walkable {
void walk();
}

interface Swimmable {
void swim();
}

class Human implements Walkable, Swimmable {


public void walk() {
System.out.println("Human is walking");
}

public void swim() {


System.out.println("Human is swimming");
}
}

public class Mul pleInheritanceExample {


public sta c void main(String[] args) {
Human person = new Human();
person.walk(); // Inherited from Walkable
person.swim(); // Inherited from Swimmable
}
}

3. Hierarchical Inheritance:
 Defini on:
When several classes derive from a single superclass, this is known as
hierarchical inheritance.
 Syntax:
// Superclass
class Animal {
// Fields and methods of the superclass
}

// Subclass 1 inheri ng from the superclass


class Dog extends Animal {
// Addi onal fields and methods of the subclass
}

// Subclass 2 inheri ng from the superclass


class Cat extends Animal {
// Addi onal fields and methods of the subclass
}

 Example:
// Hierarchical Inheritance Example
class Animal {
void eat() {
System.out.println("Animal is ea ng");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

class Cat extends Animal {


void meow() {
System.out.println("Cat is meowing");
}
}

public class HierarchicalInheritanceExample {


public sta c void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog

Cat myCat = new Cat();


myCat.eat(); // Inherited from Animal
myCat.meow(); // Defined in Cat
}
}
Program
// Superclass
class Vehicle {
// Fields
String brand;
int year;

// Constructor
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}

// Method
public void displayInfo() {
System.out.println("Vehicle Informa on:");
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}

// Subclass Car inheri ng from Vehicle


class Car extends Vehicle {
// Addi onal fields
String model;
// Constructor
public Car(String brand, String model, int year) {
// Call the superclass constructor using 'super'
super(brand, year);
this.model = model;
}

// Addi onal method


public void drive() {
System.out.println("The car is now driving.");
}
}

// Subclass Bicycle inheri ng from Vehicle


class Bicycle extends Vehicle {
// Addi onal fields
int gears;

// Constructor
public Bicycle(String brand, int gears, int year) {
// Call the superclass constructor using 'super'
super(brand, year);
this.gears = gears;
}
// Addi onal method
public void pedal() {
System.out.println("The bicycle is now pedaling.");
}
}

// Main class
public class InheritanceProgram {
public sta c void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Toyota", "Camry", 2022);

// Access fields and methods from both superclass and subclass


myCar.displayInfo(); // Access method from superclass
myCar.drive(); // Access method from subclass

System.out.println(); // Separate car and bicycle outputs

// Create an object of the Bicycle class


Bicycle myBicycle = new Bicycle("Giant", 5, 2022);

// Access fields and methods from both superclass and subclass


myBicycle.displayInfo(); // Access method from superclass
myBicycle.pedal(); // Access method from subclass
}
}

In this program:
- The `Vehicle` class is the superclass with fields and a method to display vehicle
informa on.
- The `Car` class is a subclass of `Vehicle` with addi onal fields and a method.
- The `Bicycle` class is another subclass of `Vehicle` with its own set of addi onal
fields and a method.
- The `InheritanceProgram` class demonstrates the crea on of objects of both the
`Car` and `Bicycle` classes, showcasing the inheritance rela onship.

1.13 Method overriding


1. Method Overriding in Java:
 Defini on:
Object-oriented programming allows for a feature called "method overriding," in
which a subclass implements a method that is already defined in its superclass
in a certain way. It permits a subclass to offer a method in a more specialized
form.
 Syntax:
// Superclass
class Superclass {
returnType methodName(parameters) {
// Superclass method implementa on
}
}

// Subclass overriding the method


class Subclass extends Superclass {
@Override
returnType methodName(parameters) {
// Subclass method implementa on (override)
}
}

2. Example of Method Overriding:


Let's consider a scenario with a `Shape` superclass and a `Circle` subclass:
 Superclass (Shape):
// Superclass
class Shape {
double calculateArea() {
return 0; // Default implementa on (to be overridden)
}
}

 Subclass (Circle):
// Subclass
class Circle extends Shape {
double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Overriding the method from the superclass


@Override
double calculateArea() {
return Math.PI radius radius;
}
}

 Using Method Overriding:


// Main class
public class MethodOverridingExample {
public sta c void main(String[] args) {
// Create an object of the subclass (Circle)
Circle myCircle = new Circle(5.0);

// Call the overridden method


double area = myCircle.calculateArea();

// Display the result


System.out.println("Area of the circle: " + area);
}
}

3. Complete Program:
Here is the complete Java program that demonstrates method overriding:

// Superclass
class Shape {
double calculateArea() {
return 0; // Default implementa on (to be overridden)
}
}

// Subclass
class Circle extends Shape {
double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Overriding the method from the superclass


@Override
double calculateArea() {
return Math.PI radius radius;
}
}

// Main class
public class MethodOverridingExample {
public sta c void main(String[] args) {
// Create an object of the subclass (Circle)
Circle myCircle = new Circle(5.0);

// Call the overridden method


double area = myCircle.calculateArea();

// Display the result


System.out.println("Area of the circle: " + area);
}
}

1.14 Abstract Classes


1. Abstract Class in Java:
 Defini on:
In Java, an abstract class is one that lacks the ability to instan ate itself and can
have methods with no body, or abstract methods. Concrete and abstract
methods can both be found in abstract classes, which act as a model for other
classes.
 Syntax:
// Abstract class
abstract class AbstractClass {
// Abstract method (no implementa on)
abstract void abstractMethod();

// Concrete method with implementa on


void concreteMethod() {
// Implementa on
}
}

2. Abstract Method:
 Defini on:
A method expressed in an abstract class but lacking a body is called an abstract
method. Abstract methods require an implementa on, which subclasses must
supply.
 Syntax:
// Abstract class with an abstract method
abstract class AbstractClass {
abstract void abstractMethod();
}

3. Example of Abstract Class:


Let's consider an example involving a shape hierarchy with an abstract class `Shape`:
 Abstract Class (Shape):
// Abstract class
abstract class Shape {
// Abstract method for calcula ng area
abstract double calculateArea();

// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

 Subclass (Circle):
// Subclass extending the abstract class
class Circle extends Shape {
double radius;

// Constructor
public Circle(double radius) {
this.radius = radius;
}

// Implementa on of the abstract method


@Override
double calculateArea() {
return Math.PI radius radius;
}
}

 Using Abstract Class:


// Main class
public class AbstractClassExample {
public sta c void main(String[] args) {
// Create an object of the subclass (Circle)
Circle myCircle = new Circle(5.0);

// Call the overridden method


double area = myCircle.calculateArea();

// Display the result


System.out.println("Area of the circle: " + area);

// Call the concrete method from the abstract class


myCircle.display();
}
}

4. Benefits of Abstract Classes:


 Encapsula on of Common Behavior: Abstract classes allow encapsula on of
common behavior and a ributes shared among subclasses.
 Enforcement of Method Implementa on: Abstract classes can enforce that
subclasses provide specific method implementa ons.
 Polymorphism: Abstract classes support polymorphism, allowing objects of
different concrete subclasses to be treated as objects of the abstract class.

1.15 Interfaces, Extending Interfaces & Accessing Interface variables.


1. Interfaces in Java:
 Defini on:
An interface in Java is a collec on of abstract methods, providing a way to achieve
abstrac on. It specifies a contract for classes to implement, without defining
the implementa on details. Interfaces can also include constants (fields with a
`final` modifier).
 Syntax:
// Interface
interface MyInterface {
// Abstract method(s)
returnType methodName(parameters);

// Constant(s)
dataType CONSTANT_NAME = value;
}
2. Extending Interfaces:
 Defini on:
In Java, an interface can extend another interface, inheri ng its abstract methods
and constants. This allows for the crea on of a hierarchy of interfaces.
 Syntax:
// Interface extending another interface
interface MyExtendedInterface extends AnotherInterface {
// Addi onal abstract method(s) and constant(s)
}

3. Accessing Interface Variables:


 Defini on:
Interface variables are implicitly `public`, `sta c`, and `final`. They can be accessed
directly through the interface, without crea ng an instance of it.
 Syntax:
// Accessing interface variable
dataType variableName = InterfaceName.CONSTANT_NAME;

4. Example of Interfaces and Extending Interfaces:


Consider an example involving a `Drawable` interface and a `Resizable` interface
extending it:
 Interface (Drawable):
// Interface
interface Drawable {
// Abstract method for drawing
void draw();

// Constant
String COLOR = "Red";
}

 Interface (Resizable) extending Drawable:


// Interface extending another interface
interface Resizable extends Drawable {
// Addi onal abstract method for resizing
void resize(int percentage);

 Using Interfaces:
// Class implemen ng the interfaces
class Shape implements Resizable {
// Implementa on of draw method
@Override
public void draw() {
System.out.println("Drawing a shape with color: " + COLOR);
}

// Implementa on of resize method


@Override
public void resize(int percentage) {
System.out.println("Resizing the shape by " + percentage + "%");
}
}

 Accessing Interface Variables:


// Accessing interface variable
String color = Resizable.COLOR;

In this example:
- The `Drawable` interface defines an abstract method `draw` and a constant
`COLOR`.
- The `Resizable` interface extends `Drawable` and adds an abstract method `resize`.
- The `Shape` class implements the interfaces and provides implementa ons for the
abstract methods.
- The `color` variable is accessed directly from the interface.

 Knowledge Check 2
State True or False
1. "In Java, an object is an instance of a class." (True)
2. "Garbage collec on in Java is a manual process where the developer has to
explicitly deallocate memory." (False)
3. "The `finalize()` method is called by the programmer to ini ate garbage
collec on." (False)
4. "In Java, a subclass can inherit both a ributes and methods from mul ple
superclasses simultaneously." (False)
5. "Method overriding in Java allows a subclass to provide a specific
implementa on for a method that is already defined in its superclass." (True)
 Outcomes-Based Ac vity 2
Apply and demonstrate understanding of key Java concepts such as classes,
objects, inheritance, method overriding, abstract classes, interfaces, garbage
collec on, and finalize() method. For Design a program that represents different
geometric shapes, u lizing class hierarchy, inheritance, and interfaces.

1.16 Summary
 A feature-rich language with Object-Oriented paradigm, pla orm
independence, simple syntax, robust security, mul threading, and support for
distributed compu ng.
 Differen ates from C++ through pla orm independence, no explicit pointers,
automa c garbage collec on, avoidance of operator overloading, and use of
interfaces for mul ple inheritance.
 Program structure includes class declara on, main method, package
organiza on, and comments for documenta on.
 Tokens encompass keywords, iden fiers, literals, operators, separators, and
comments for code clarity.
 The Java Virtual Machine (JVM) provides a pla orm-independent execu on
environment, interpre ng bytecode, managing memory, and enforcing security.
 Constants, variables, and data types define the founda on for storing and
manipula ng data.
 Operators and expressions handle opera ons on variables and literals.
 Control structures, including condi onal and looping statements, govern
program flow.
 Arrays act as a data structure, allowing the collec on and indexing of elements.
 Classes and objects form the core of Java, with constructors ini alizing object
proper es.
 Garbage collec on automa cally manages memory by reclaiming unused
objects.
 Inheritance involves the crea on of subclasses inheri ng proper es from a
superclass.
 Method overriding allows specific implementa ons in subclasses.
 Abstract classes feature abstract and concrete methods for structured code.
 Interfaces combine abstract methods and constants, suppor ng extension and
direct access to interface variables.

1.17 Keywords
 Java Features: This keyword refers to the dis nc ve characteris cs of the Java
programming language. Java is known for its portability, object-oriented nature,
pla orm independence, automa c memory management (garbage collec on),
robust security features, and support for mul threading. These features make
Java a versa le and widely-used programming language.
 Java vs. C++: This sec on highlights the differences between Java and C++. Key
differences include Java's pla orm independence through bytecode and the
Java Virtual Machine (JVM), automa c memory management (garbage
collec on) as opposed to C++'s manual memory management, and Java's
simpler syntax. Java also avoids explicit use of pointers and mul ple inheritance,
which are features present in C++.
 Java Program Structure: This keyword encompasses the essen al components
of a Java program's structure. It includes class declara ons, the main method,
the use of packages for organiza on, and the importance of comments for
documenta on. Understanding these elements is fundamental to wri ng well-
organized Java programs.
 Java Virtual Machine (JVM): The JVM is a crucial component of Java's
architecture. It's responsible for execu ng Java bytecode, providing a pla orm-
independent run me environment. The JVM plays a key role in memory
management, security enforcement, and ensuring Java's pla orm
independence.
 Garbage Collec on: This term refers to Java's process of automa c memory
management. The garbage collector in Java automa cally iden fies and discards
objects that are no longer in use, thus preven ng memory leaks and op mizing
memory usage. Understanding garbage collec on is important for efficient Java
programming.

1.18 Self-Assessment Ques ons


1. What are the main features that define Java as an object-oriented programming
language?
2. How does Java achieve pla orm independence, and why is it important?
3. Enumerate the key differences between Java and C++, focusing on pla orm
independence and memory management.
4. Explain the significance of Java not suppor ng explicit pointers.
5. What are the essen al components of the structure of a Java program?
6. Why is it recommended to organize Java code into packages?
7. Define and provide examples of Java keywords, iden fiers, literals, and
operators.
8. How do comments contribute to code documenta on in Java?
9. Explain the role of the JVM in making Java a pla orm-independent language.
10.Briefly discuss the responsibili es of the Java Virtual Machine in terms of
memory management and security.

1.19 References / Reference Reading


 Joshua Bloch, "Effec ve Java", Addison-Wesley, 2008.
 Herbert Schildt, "Java: The Complete Reference", McGraw-Hill Educa on, 2018.
 Kathy Sierra and Bert Bates, "Head First Java", O'Reilly Media, 2005.
 Bruce Eckel, "Thinking in Java", Pren ce Hall, 2006.

You might also like