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

Notes Java

The document provides an overview of the history and evolution of Java, including its origins in the 1990s, major releases, adoption, and future directions. It also covers topics like installing the JDK, Java naming conventions, and data types in Java.

Uploaded by

imayush476
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Notes Java

The document provides an overview of the history and evolution of Java, including its origins in the 1990s, major releases, adoption, and future directions. It also covers topics like installing the JDK, Java naming conventions, and data types in Java.

Uploaded by

imayush476
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Module-1 (Fundamentals)

History and evolution of Java:


Java is a versatile, object-oriented programming language that has had a significant impact on software development since its inception.
Here's a brief overview of its history and evolution:

1. Origins (mid-1990s):
Java was developed by James Gosling and his team at Sun Microsystems (later acquired by Oracle Corporation) in the early 1990s.
It was originally designed for interactive television, but Sun Microsystems recognized its potential in the emerging internet era.
2. Introduction (1995):
Java was officially released to the public in 1995. Its slogan was "Write Once, Run Anywhere" (WORA), emphasizing its platform
independence.
Java's ability to run on any device with the Java Virtual Machine (JVM) made it particularly attractive for web development and other cross-
platform applications.
3. Evolution of the Java Platform:
a. J2SE (Java 2 Platform, Standard Edition): Introduced in December 1998, it brought significant enhancements and new
features, including Swing GUI toolkit, JDBC (Java Database Connectivity), and more.
b. J2EE (Java 2 Platform, Enterprise Edition): Aimed at enterprise applications, it provided tools and APIs for building
large-scale, distributed applications.
c. J2ME (Java 2 Platform, Micro Edition): Tailored for mobile and embedded devices, it enabled developers to create
applications for devices with limited resources.
4. Major Releases:
a. Java 5 (2004): Introduced generics, metadata annotations, enumerated types, and the enhanced for loop.
b. Java 6 (2006): Focus on performance improvements, including faster startup time and lower memory consumption.
c. Java 7 (2011): Introduces features like the try-with-resources statement, diamond operator, and improvements to the
concurrency API.
d. Java 8 (2014): A major release introducing lambda expressions, the Stream API, and the java.time package for
date/time manipulation.
e. Java 9 (2017): Introduces the module system (Project Jigsaw), enhancing scalability, maintainability, and
performance.
f. Java 10 (2018): Introduced local variable type inference (var), enhancing developer productivity.
g. Java 11 (2018): Long-term support (LTS) release with updates including HTTP client API and improvements to the
garbage collector.
h. Java 12-17 (2019-2021): Continued incremental updates with new features and improvements, including switch
expressions, text blocks, and records.

5. Open Sourcing and Community Involvement:


In 2006, Sun Microsystems open-sourced the Java platform, leading to the creation of the OpenJDK (Java Development Kit).
The Java Community Process (JCP) was established to guide the evolution of the Java platform in an open and collaborative manner,
involving various stakeholders.

6. Adoption and Popularity:


Java has become one of the most widely used programming languages globally, powering a vast array of applications ranging from
enterprise systems to mobile apps and web services.
It remains popular due to its portability, strong community support, extensive libraries, and robustness.

7. Future Directions:
Oracle and the Java community continue to work on evolving the Java platform, with ongoing efforts to improve performance, security, and
developer productivity.

JVM:
Installing Java Development Kit (JDK):
Installing the Java Development Kit (JDK) typically involves a few straightforward steps. Here's a general guide:

1. Download the JDK:


Visit the official Oracle website or the OpenJDK website to download the JDK.
Choose the appropriate version of the JDK for your operating system (Windows, macOS, or Linux) and architecture (32-bit or 64-bit).
Make sure to select the JDK, not just the JRE (Java Runtime Environment), as the JDK includes tools needed for Java development, such as
the compiler (javac) and the Java Development Kit (java).

2. Run the Installer:


Once the JDK installer is downloaded, run the executable file to start the installation process.
Follow the on-screen instructions provided by the installer. These may vary slightly depending on your operating system.
3. Choose Installation Directory:
During the installation process, you may be prompted to choose the installation directory for the JDK. The default directory is typically fine
for most users, but you can choose a different location if desired.

4. Complete the Installation:


After selecting the installation directory, the installer will copy the necessary files and set up the JDK on your system.
Once the installation is complete, you may be presented with an option to install additional components or configure the JDK. Follow the
prompts to complete any additional setup steps.

5. Set up Environment Variables (Optional):


On some operating systems, you may need to manually set up environment variables to ensure that your system can locate the JDK
executables (java, javac, etc.).

For example, on Windows, you may need to set the JAVA_HOME environment variable to point to the directory where the JDK is
installed, and add the JDK's bin directory to the system's PATH variable.

6. Verify the Installation:


Once the installation is complete, open a command prompt or terminal window and run the following commands to verify that the JDK is
installed correctly:
java -version
javac -version

These commands should display the version numbers of the Java runtime and compiler, respectively, indicating that the JDK is installed and
configured correctly.

Setting up the Path and Classpath:

Understanding the java directory structure:

Understanding Java source file structure:

Java Naming Conventions:


1. Class Names:
 Start with an uppercase letter.
 Use nouns or noun phrases, and capitalize the first letter of each word.
 Avoid underscores (except in special cases).
 Example: MyClass, StudentRecord, EmployeeDetails.
 Follow the same conventions as class names.
 Use adjectives or adjective phrases to name interfaces.
 Example: Runnable, Serializable, Comparable.

2. Method Names:
 Start with a lowercase letter.
 Use verbs or verb phrases, and capitalize the first letter of each word thereafter.
 Follow camelCase convention.
 Example: calculateSalary(), printDetails(), getUserInput().

3. Variable Names:
 Start with a lowercase letter.
 Use meaningful names that describe the variable's purpose.
 Follow camelCase convention.
 Example: firstName, totalAmount, numberOfStudents.

4. Constant Names:
 Use uppercase letters.
 Separate words with underscores.
 Example: MAX_VALUE, PI, DEFAULT_TIMEOUT.

5. Package Names:
 Use lowercase letters.
 Use a reversed domain name to prevent naming conflicts.
 Example: com.example.myproject, org.openai.gpt.

6. Enum Names:
 Follow the same conventions as class names.
 Use singular nouns or noun phrases.
 Example: DayOfWeek, Color.
7. Parameter Names:
 Follow the same conventions as variable names.
 Use meaningful names that describe the parameter's purpose.
 Example: radius, numItems, username.

8. Local Variable Names:


 Follow the same conventions as variable names.
 Use meaningful names that describe the variable's purpose within its scope.
 Example: index, tempValue, result.

Data Types:
Primitive Data Types:
Primitive data types are basic data types provided by Java. They are used to store simple values.

Java has eight primitive data types:


 byte: 8-bit signed integer. Range: -128 to 127.
 short: 16-bit signed integer. Range: -32,768 to 32,767.
 int: 32-bit signed integer. Range: -2^31 to 2^31 - 1.
 long: 64-bit signed integer. Range: -2^63 to 2^63 - 1.
 float: 32-bit floating-point. Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits.
 double: 64-bit floating-point. Stores fractional numbers with higher precision. Sufficient for storing 15 decimal digits.
 char: 16-bit Unicode character. Represents a single character.
 boolean: Represents true or false.

Reference Data Types:


Reference data types are used to refer to objects. They store references to memory locations where the data is stored rather than the data
itself. Some common reference data types include:

 Object: The superclass of all classes in Java.


 String: Represents a sequence of characters.
 Array: Represents a collection of elements of the same type.
 Class: Represents classes and interfaces in Java.
 Interface: Represents interfaces.
 Enum: Represents enumerated types.

Primitive vs. Reference Data Types:


 Primitive data types are stored directly in memory, while reference data types store references to objects in memory.
 Primitive data types are faster to access and require less memory compared to reference data types.
 Primitive data types cannot be null, while reference data types can be null.

In Java, data types are crucial for declaring variables, defining methods, and creating classes. Understanding the differences between
primitive and reference data types is fundamental for writing efficient and correct Java programs.

Variables, and literals:


Variables in Java can be categorized into several types based on their scope, lifetime, and whether they are primitive or reference types:

Local Variables: Declared within a method or a block of code. They have a limited scope and are accessible only within the block where
they are declared.

int age = 25; // Example of a local variable


Instance Variables (Non-static Fields): Belong to an instance of a class and are declared within the class but outside any method,
constructor, or block.

public class MyClass {


int x; // Instance variable
}

Class Variables (Static Fields): Shared among all instances of a class. There is only one copy of a class variable, regardless of how many
objects are created from the class.

public class MyClass {


static int count; // Class variable
}
Literals:
Literals are fixed values that are directly used in the code. Java supports various types of literals:
Integer Literals: Whole numbers without any fractional part. Can be specified in decimal (base 10), octal (base 8), or hexadecimal (base 16)
format.
int decimal = 10;
int octal = 010; // Octal representation (8 in decimal)
int hex = 0x10; // Hexadecimal representation (16 in decimal)

Floating-Point Literals: Numbers with fractional parts. Can be specified using decimal notation.
double d = 10.5;
float f = 3.14f; // Floating-point literals are treated as double by default, so need 'f' suffix for float

Boolean Literals: Represent the logical values true or false


boolean b1 = true;
boolean b2 = false;

Character Literals: Single characters enclosed in single quotes.


char ch = 'A';

String Literals: Sequences of characters enclosed in double quotes.


String str = "Hello, World!";

Null Literal: Represents a null reference.


MyClass obj = null;

Operators and Expressions:

` Arithmetic Operators:

Addition (+): Adds two operands.

int sum = a + b;

Subtraction (-): Subtracts the second operand from the first.

int difference = a - b;

Multiplication (*): Multiplies two operands.

int product = a * b;

Division (/): Divides the first operand by the second.

int quotient = a / b;

Modulus (%): Returns the remainder of the division.

int remainder = a % b;

Relational Operators:

Equal to (==): Checks if two operands are equal.

boolean isEqual = (a == b);

Not equal to (!=): Checks if two operands are not equal.

boolean notEqual = (a != b);

Greater than (>): Checks if the first operand is greater than the second.

boolean isGreater = (a > b);

Less than (<): Checks if the first operand is less than the second.

boolean isLess = (a < b);

Greater than or equal to (>=): Checks if the first operand is greater than or equal to the second.

boolean isGreaterOrEqual = (a >= b);

Less than or equal to (<=): Checks if the first operand is less than or equal to the second.

boolean isLessOrEqual = (a <= b);

Logical Operators:

AND (&&): Returns true if both operands are true.


boolean result = (a > 0 && b < 10);

OR (||): Returns true if at least one operand is true.

boolean result = (a > 0 || b < 10);

NOT (!): Returns the opposite of the operand's value.

boolean result = !(a > 0);

Assignment Operators:

Assignment (=): Assigns a value to a variable.

int x = 10;

Addition assignment (+=): Adds right operand to the left operand and assigns the result to the left operand.

x += 5; // Equivalent to x = x + 5;

Subtraction assignment (-=): Subtracts right operand from the left operand and assigns the result to the left operand.

x -= 5; // Equivalent to x = x - 5;

Multiplication assignment (*=): Multiplies right operand with the left operand and assigns the result to the left operand.

x *= 5; // Equivalent to x = x * 5;

Division assignment (/=): Divides left operand with the right operand and assigns the result to the left operand.

x /= 5; // Equivalent to x = x / 5;

Increment and Decrement Operators:

Increment (++): Increases the value of a variable by 1.

x++; // Equivalent to x = x + 1;

Decrement (--): Decreases the value of a variable by 1.

x--; // Equivalent to x = x - 1;

Control flow statements (if-else, switch, loops)


Conditional Statements:
if-else:
if (condition) {
// code block executed if condition is true
} else {
// code block executed if condition is false
}

if-else if-else:
if (condition1) {
// code block executed if condition1 is true
} else if (condition2) {
// code block executed if condition2 is true
} else {
// code block executed if neither condition1 nor condition2 is true
}

Switch Statement:

switch (expression) {
case value1:
// code block executed if expression equals value1
break;
case value2:
// code block executed if expression equals value2
break;
// add more cases as needed
default:
// code block executed if expression doesn't match any case
}
Loops:
for Loop:

for (initialization; condition; update) {


// code block to be executed
}
In addition to the basic for loop in Java, there are other variants such as the enhanced for
loop (also known as the "for-each" loop) and the "for loop" introduced in Java 5. Let's
explore these variants:
Enhanced for Loop (for-each Loop):
The enhanced for loop simplifies iteration over arrays and collections. It is particularly useful
when you want to iterate through each element of an array or a collection without needing
to keep track of the index.
Syntax:
for (type variable : array) {
// code block to be executed for each element
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
"for loop" introduced in Java 5:
In Java 5, a new form of the for loop was introduced, known as the "for-each" loop. It's
similar to the enhanced for loop but can be used with iterators, enumerations, and
collections.
Syntax:
for (type variable : iterable) {
// code block to be executed for each element
}
Example with ArrayList:
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

for (String name : names) {


System.out.println(name);
}

while Loop:
while (condition) {
// code block to be executed
}

do-while Loop:
do {
// code block to be executed
} while (condition);

Branching Statements:
break:
Terminates the loop or switch statement it's in.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
// code block to be executed
}
continue:
Skips the current iteration of a loop and continues with the next iteration.

for (int i = 0; i < 10; i++) {


if (i == 5) {
continue;
}
// code block to be executed
}

return:
Exits from the current method and optionally returns a value.
public int someMethod() {
// code block
if (condition) {
return value;
}
// code block
}

Java Keywords:
Keyword Usage

Specifies that a class or method will be implemented later, in a


abstract
subclass

Assert describes a predicate placed in a Java program to indicate


assert that the developer thinks that the predicate is always true at that
place.

boolean A data type that can hold True and False values only

break A control statement for breaking out of loops.

byte A data type that can hold 8-bit data values

case Used in switch statements to mark blocks of text

catch Catches exceptions generated by try statements

char A data type that can hold unsigned 16-bit Unicode characters

class Declares a new class

continue Sends control back outside a loop

default Specifies the default block of code in a switch statement

do Starts a do-while loop


Keyword Usage

double A data type that can hold 64-bit floating-point numbers

else Indicates alternative branches in an if statement

A Java keyword is used to declare an enumerated type.


enum
Enumerations extend the base class.

extends Indicates that a class is derived from another class or interface

Indicates that a variable holds a constant value or that a method


final
will not be overridden

Indicates a block of code in a try-catch structure that will always


finally
be executed

float A data type that holds a 32-bit floating-point number

for Used to start a for loop

if Tests a true/false expression and branches accordingly

implements Specifies that a class implements an interface

import References other classes

Indicates whether an object is an instance of a specific class or


instanceof
implements an interface

int A data type that can hold a 32-bit signed integer

interface Declares an interface

long A data type that holds a 64-bit integer

Specifies that a method is implemented with native (platform-


native
specific) code

new Creates new objects


Keyword Usage

null This indicates that a reference does not refer to anything

package Declares a Java package

An access specifier indicating that a method or variable may be


private
accessed only in the class it’s declared in

An access specifier indicating that a method or variable may only


protected be accessed in the class it’s declared in (or a subclass of the class
it’s declared in or other classes in the same package)

An access specifier used for classes, interfaces, methods, and


public variables indicating that an item is accessible throughout the
application (or where the class that defines it is accessible)

Sends control and possibly a return value back from a called


return
method

short A data type that can hold a 16-bit integer

Indicates that a variable or method is a class method (rather than


static
being limited to one particular object)

A Java keyword is used to restrict the precision and rounding of


strictfp
floating-point calculations to ensure portability.

Refers to a class’s base class (used in a method or class


super
constructor)

switch A statement that executes code based on a test value

synchronized Specifies critical sections or methods in multithreaded code

this Refers to the current object in a method or constructor

throw Creates an exception

throws Indicates what exceptions may be thrown by a method


Keyword Usage

transient Specifies that a variable is not part of an object’s persistent state

try Starts a block of code that will be tested for exceptions

void Specifies that a method does not have a return value

volatile This indicates that a variable may change asynchronously

while Starts a while loop

Declaring and Initializing Arrays:


// Declaring an array of integers with size 5 and initializing it
int[] numbers = new int[5];

// Declaring and initializing an array of integers with specific values


int[] numbers = {1, 2, 3, 4, 5};

// Declaring an array of integers with size 5


int[] numbers;
// Initializing the array later
numbers = new int[5];

// Declaring and initializing a 2D array


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

// Declaring and initializing an array without storing it in a variable


int[] numbers = new int[] {1, 2, 3, 4, 5};

// Initializing an array with Arrays.fill() method


int[] numbers = new int[5];
Arrays.fill(numbers, 0); // This will fill the array with zeros
// Initializing an array using a loop
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}

Array Manipulation (sorting, searching):

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
int[] arr = {5, 2, 9, 1, 3};
Arrays.sort(arr); // Sorts the array in ascending order
System.out.println(Arrays.toString(arr)); // Prints: [1, 2, 3, 5, 9]
}
}
import java.util.Arrays;
import java.util.Comparator;

public class Main {


public static void main(String[] args) {
Integer[] arr = {5, 2, 9, 1, 3};
Arrays.sort(arr, Comparator.reverseOrder()); // Sorts the array in
descending order
System.out.println(Arrays.toString(arr)); // Prints: [9, 5, 3, 2, 1]
}
}

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 5, 9};
int index = Arrays.binarySearch(arr, 5); // Searches for element 5 in the
sorted array
System.out.println("Index of 5: " + index); // Prints: Index of 5: 3
}
}

STRING
String:

In Java, String is a class that represents a sequence of characters. It's a


fundamental and widely used data type in Java programming. Here are some
key points about the String class:

Immutable: Once a String object is created, it cannot be changed. Any


operation that appears to modify the String actually creates a new String
object.

Declared in java.lang package: The String class is part of the java.lang package,
which is automatically imported into every Java program. This means you can
use String without explicitly importing it.

String greeting = "Hello, World!";

String firstName = "John";


String lastName = "Doe";
String fullName = firstName + " " + lastName;

String manipulation and methods:


String str = "Hello";
int length = str.length(); // length is 5

char ch = str.charAt(0); // ch is 'H'

char[] charArray = str.toCharArray();

String fullName = firstName + " " + lastName;


String joined = String.join("-", "2018", "01", "01"); // joined is "2018-01-01"

String upperCase = str.toUpperCase();


String lowerCase = str.toLowerCase();

int index = str.indexOf("lo"); // index is 3

boolean isEqual = str.equals("Hello");


boolean isEqualIgnoreCase = str.equalsIgnoreCase("hello");

String replaced = str.replace('l', 'z'); // replaced is "Hezzo"

String trimmed = " Hello ".trim(); // trimmed is "Hello"

String sub = str.substring(1, 3); // sub is "el"

String[] parts = str.split(" "); // Splits by space

String formatted = String.format("Name: %s, Age: %d", name, age);

StringBuilder sb = new StringBuilder();


sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString(); // result is "Hello World"

CLASS AND OBJECT:


 A class defines a type, while an object is an instance of that type.
 A class provides the structure and behavior, while an object represents
the specific instance of that structure with its own state.
 Classes are used to create objects, and objects interact with each other
to accomplish tasks in a program.

ENCAPSULATION:
Encapsulation is one of the four fundamental principles of object-oriented
programming (OOP), along with inheritance, polymorphism, and abstraction. It
refers to the bundling of data (attributes) and methods (behaviors) that
operate on the data into a single unit, known as a class. Encapsulation hides
the internal state of an object from the outside world and only exposes the
necessary functionality through well-defined interfaces.
Key Concepts of Encapsulation:
 Data Hiding: Encapsulation allows data to be hidden from outside
access, preventing direct manipulation of an object's internal state. This
is achieved by declaring the fields of a class as private and providing
public methods (getters and setters) to access and modify the data.

 Access Modifiers: In Java, access modifiers such as private, public,


protected, and default are used to control the visibility of fields and
methods. By marking fields as private, they can only be accessed and
modified by methods within the same class.

 Information Hiding: Encapsulation promotes information hiding by


exposing only essential information about an object's behavior and
hiding the implementation details. This reduces complexity, enhances
security, and improves maintainability by preventing unintended
changes to the internal state of an object.
 Abstraction: Encapsulation is closely related to abstraction, as it allows
the implementation details to be abstracted away from the external
interfaces. Clients interacting with an object do not need to know how
the object's methods are implemented internally, only how to use them.

Benefits of Encapsulation:
 Modularity: Encapsulation promotes modularity by organizing code into
self-contained units (classes) that can be developed, tested, and
maintained independently.

 Security: By hiding the internal state of an object, encapsulation


prevents unauthorized access and manipulation of data, enhancing
security.

 Flexibility: Encapsulation allows the internal implementation of a class


to change without affecting the external code that uses the class. This
promotes code flexibility and adaptability to future changes.

 Code Reusability: Encapsulation facilitates code reusability by providing


well-defined interfaces that can be used by other classes without
knowledge of the internal implementation.

 Maintainability: Encapsulation improves code maintainability by


localizing changes within the class implementation, reducing the risk of
unintended side effects in other parts of the codebase.

EXAMPLE:
public class Person {
// Private fields (attributes)
private String name;
private int age;
private String gender;

// Constructor
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {


return age;
}

public String getGender() {


return gender;
}

// Setter methods
public void setName(String name) {
this.name = name;
}

public void setAge(int age) {


this.age = age;
}

public void setGender(String gender) {


this.gender = gender;
}
}
INHERITANCE:
Inheritance is a fundamental concept in object-oriented programming (OOP)
that allows a class (subclass or child class) to inherit the properties and
behaviors (fields and methods) of another class (superclass or parent class). In
Java, inheritance enables code reusability and promotes the creation of
hierarchies of classes.

Key Concepts of Inheritance:


Syntax: To inherit from a class, you use the extends keyword in the class
declaration.
class Subclass extends Superclass {
// subclass members
}
Single Inheritance: Java supports single inheritance, meaning a class can
inherit from only one superclass.
Superclass (Parent class): The class whose members are inherited is called the
superclass or parent class.
Subclass (Child class): The class that inherits the members from the superclass
is called the subclass or child class.
Access Modifiers: Subclasses inherit all visible fields and methods from their
superclass except constructors. Access modifiers control the visibility of
inherited members:
 public: Inherited members are accessible by any other class.
 protected: Inherited members are accessible within the same
package and by subclasses (even if they're in different packages).
 default (no modifier): Inherited members are accessible only
within the same package.
 private: Inherited members are not accessible in subclasses.

Constructor Inheritance: Constructors are not inherited by subclasses, but


they are called implicitly or explicitly in the subclass constructors using super().
Method Overriding: Subclasses can provide a specific implementation of a
method that is already defined in its superclass. This is known as method
overriding. Rules for method overriding include:

The method signature (name and parameters) in the subclass must match the
method signature in the superclass.
The return type of the overriding method can be the same as, or a subtype of,
the return type in the superclass.
The access level of the overriding method in the subclass can't be more
restrictive than the access level in the superclass.
Keyword super: The super keyword is used to access members (fields,
methods, and constructors) of the superclass from within the subclass. It's also
used to call the superclass constructor explicitly.

Final Classes and Methods: The final keyword can be used to prevent a class
from being subclassed or a method from being overridden.

Object Class: All classes in Java implicitly inherit from the Object class, which is
the root of the class hierarchy in Java.

Abstract Classes and Interfaces: Abstract classes and interfaces are used to
define contracts for subclasses, promoting polymorphism and abstraction in
Java. Subclasses must implement all abstract methods defined in abstract
classes or interfaces.

Access Modifiers:
Inherited members (fields and methods) of the superclass can have different
access modifiers:
 public: accessible from anywhere
 protected: accessible within the same package and subclasses
 default (no modifier): accessible within the same package
 private: not accessible in subclasses

Single Inheritance:
Java supports single inheritance, meaning a subclass can inherit from only one
superclass. However, a superclass can have multiple subclasses.
Super Keyword:
 The super keyword is used to access members of the superclass from
within the subclass.
 It can be used to call the superclass constructor, access superclass
methods, and access superclass fields if they are not overridden.

Method Overriding:
 Subclasses can provide a specific implementation for methods inherited
from the superclass. This is known as method overriding.
 The method signature (name, parameters, return type) must be the
same in both the superclass and subclass for overriding.
 Methods marked with the final or private modifier cannot be
overridden.
Constructor Chaining:
 Subclass constructors implicitly call a superclass constructor.
 If no explicit call to a superclass constructor is made using super(), the
compiler inserts a call to the superclass's default constructor (super()).

Benefits of Inheritance:
 Code Reusability: Inheritance allows subclasses to inherit fields and
methods from the superclass, promoting code reuse and reducing
redundancy.

 Polymorphism: Inheritance facilitates polymorphism, where a subclass


can be treated as an instance of its superclass, enabling dynamic method
dispatch.

 Organizing Code: Inheritance helps organize classes into hierarchies,


reflecting real-world relationships and promoting modularity and
maintainability.

 Extensibility: Subclasses can extend the functionality of the superclass by


adding new methods or overriding existing ones.

// Superclass in package "mypackage"


package mypackage;

public class Superclass {


public int publicField;
protected int protectedField;
int defaultField; // Default access
private int privateField;

// Methods
public void publicMethod() { }
protected void protectedMethod() { }
void defaultMethod() { }
private void privateMethod() { }
}

// Subclass in the same package "mypackage"


package mypackage;

public class Subclass extends Superclass {


public void accessFields() {
// Can access all fields
publicField = 1;
protectedField = 2;
defaultField = 3;
// privateField = 4; // Not accessible in Subclass directly
}

public void accessMethods() {


// Can access all methods
publicMethod();
protectedMethod();
defaultMethod();
// privateMethod(); // Not accessible in Subclass directly
}
}
// Subclass in a different package
package otherpackage;

import mypackage.Superclass;

public class AnotherSubclass extends Superclass {


public void accessFields() {
// Can access public and protected fields
publicField = 1;
protectedField = 2;
// defaultField = 3; // Not accessible in AnotherSubclass
// privateField = 4; // Not accessible in AnotherSubclass
}

public void accessMethods() {


// Can access public and protected methods
publicMethod();
protectedMethod();
// defaultMethod(); // Not accessible in AnotherSubclass
// privateMethod(); // Not accessible in AnotherSubclass
}
}
ABSTRACTION
Abstraction: Inheritance enables abstraction by allowing common properties
and behaviors to be defined in a superclass and specialized variations in
subclasses.

EXAMPLE:

// Superclass Vehicle
class Vehicle {
private String brand;
private String model;

public Vehicle(String brand, String model) {


this.brand = brand;
this.model = model;
}

public void drive() {


System.out.println("The " + brand + " " + model + " is driving.");
}
}

// Subclass Car
class Car extends Vehicle {
private int numberOfSeats;

public Car(String brand, String model, int numberOfSeats) {


super(brand, model); // Call superclass constructor
this.numberOfSeats = numberOfSeats;
}

// Additional method specific to Car


public void park() {
System.out.println("The " + getBrand() + " " + getModel() + " is parking.");
}
}

// Subclass Bicycle
class Bicycle extends Vehicle {
private int numberOfGears;

public Bicycle(String brand, String model, int numberOfGears) {


super(brand, model); // Call superclass constructor
this.numberOfGears = numberOfGears;
}

// Additional method specific to Bicycle


public void ride() {
System.out.println("The " + getBrand() + " " + getModel() + " is riding.");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry", 5);
car.drive(); // Output: The Toyota Camry is driving.
car.park(); // Output: The Toyota Camry is parking.

Bicycle bicycle = new Bicycle("Giant", "Talon", 21);


bicycle.drive(); // Output: The Giant Talon is driving.
bicycle.ride(); // Output: The Giant Talon is riding.
}
}

POLYMORPHISEM:
Polymorphism is a fundamental concept in object-oriented programming
(OOP) that allows objects to be treated as instances of their parent class, even
if they are instances of a subclass of that parent class. It enables a single
interface (method or function) to be used to represent different types of
objects. Polymorphism allows for flexibility and extensibility in code, facilitating
code reuse and simplifying the design of complex systems.

Types of Polymorphism:
1. Compile-Time Polymorphism (Static Binding or Method Overloading):

Method overloading allows multiple methods in the same class to have the
same name but different parameters.
The decision of which method to execute is made at compile time based on the
number and types of arguments.
class MyClass {
void display(int a) {
System.out.println("Value of a: " + a);
}

void display(int a, int b) {


System.out.println("Values of a and b: " + a + ", " + b);
}
}
2. Run-Time Polymorphism (Dynamic Binding or Method Overriding):
Method overriding allows a subclass to provide a specific implementation of a
method that is already defined in its superclass.
The decision of which method to execute is made at runtime based on the
actual type of the object.2

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks");
}
}
Benefits of Polymorphism:
 Code Reusability: Polymorphism allows for the reuse of code by enabling
the use of a single interface for multiple types of objects.

 Flexibility: It provides flexibility in designing and extending systems, as


new subclasses can be added without modifying existing code.

 Simplicity: Polymorphism simplifies code by abstracting away the


specific implementation details and focusing on the common interface.

 Extensibility: It promotes extensibility by allowing for the addition of


new functionality through method overriding in subclasses.

 Reduced Coupling: Polymorphism reduces coupling between classes, as


interactions are based on abstract interfaces rather than concrete
implementations.

EXAMPLE:

class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


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

class Square extends Shape {


@Override
void draw() {
System.out.println("Drawing a square");
}
}

public class Main {


public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Square();

shape1.draw(); // Output: Drawing a circle


shape2.draw(); // Output: Drawing a square
}
}

You might also like