JAVA ASS11
JAVA ASS11
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Example:
class BankAccount {
private double balance; // Private field, cannot be accessed directly
from outside
Key Terms:
Superclass: The class being inherited from (also called the parent
class).
Subclass: The class that inherits from the superclass (also called
the child class).
Extends Keyword: Used to indicate that one class is inheriting
from another.
Example:
class Animal {
void sound() {
System.out.println("This animal makes a sound");
}
}
// Dog class inherits from Animal class
class Dog extends Animal {
void sound() {
System.out.println("The dog barks");
}
}
Here, the Dog class inherits the sound() method from the Animal class
but overrides it to provide its specific behavior.
Note: Multiple inheritance (where a class inherits from more than one
class) is not supported in Java to avoid ambiguity (known as the
"diamond problem"). However, it can be achieved through interfaces.
Method overloading allows multiple methods with the same name but
different parameter lists (either different types or different numbers of
parameters) within the same class.
Example:
class Calculator {
// Method with two integer parameters
public int add(int a, int b) {
return a + b;
}
In this example, the add method is overloaded with different types and
numbers of parameters.
Example:
class Vehicle {
void start() {
System.out.println("The vehicle starts");
}
}
1. Abstract classes
2. Interfaces
Example:
void sleep() {
System.out.println("This animal is sleeping");
}
}
Here, Animal is an abstract class that has an abstract method sound(). The
Cat class provides an implementation for this abstract method.
Example:
interface Animal {
void sound(); // Interface method (implicitly public and abstract)
}
In this example, the Dog class implements the Animal interface and
provides a concrete implementation for the sound() method.
Conclusion
The JDK includes a wide array of tools, libraries, and utilities that help in
the development and deployment of Java applications. These components
are essential for different stages of application development, from writing
and compiling code to debugging and deploying Java programs.
The JRE is a crucial part of the JDK and is required to run Java
applications. It contains the Java Virtual Machine (JVM), core
libraries, and other files necessary to execute Java programs.
The JRE is the runtime portion of Java software, meaning that it
runs the Java program, but it doesn’t include development tools
like compilers or debuggers.
b. Java Virtual Machine (JVM)
The Java compiler (javac) is one of the most critical tools in the
JDK. It compiles Java source code files (with the .java extension)
into Java bytecode files (with the .class extension).
Bytecode is platform-independent code that can run on any
machine with a JVM. The compiler checks the code for syntax
errors and other issues before converting it into bytecode.
d. Development Tools
The JDK comes with several command-line tools for different stages of
Java application development. Here are some of the most widely used
ones:
javac: The Java compiler, used to compile Java source code into
bytecode.
java: The Java launcher, used to start the JVM and run Java
applications.
javadoc: A documentation generator that extracts comments from
the Java source code and generates API documentation in HTML
format.
jar: The Java Archive tool, used to package compiled Java classes
into a single file (typically .jar files) for easier distribution and
execution.
jdb: A command-line debugger for Java, allowing developers to
step through code, set breakpoints, and inspect variables at runtime.
javap: A Java class file disassembler that shows the bytecode and
other low-level details of compiled classes.
jshell: A Read-Eval-Print-Loop (REPL) tool introduced in JDK 9,
allowing developers to test code snippets interactively without
creating a full class or method.
jps, jstack, jmap, jstat: Performance monitoring and diagnostic
tools to help analyze and troubleshoot memory leaks, thread
deadlocks, and other performance issues.
e. Java Standard Library
The JDK has evolved significantly since its initial release. Here's a look
at the important versions and their key features:
The very first release of the JDK. It included basic tools for
developing Java applications, such as the compiler, interpreter, and
debugger.
Supported applets, which were embedded into web browsers using
Java technology.
e. JDK 7 (2011)
f. JDK 8 (2014)
g. JDK 9 (2017)
h. JDK 11 (2018)
i. JDK 17 (2021)
j. JDK 21 (2023)
Introduced features such as virtual threads (Project Loom) for
scalable concurrency, string templates, and structured
concurrency to handle parallel operations more effectively.
3. Distributions of JDK
Several organizations provide JDK distributions, each with its own set of
tools and support. These are the most widely used distributions:
a. Oracle JDK
b. OpenJDK
c. Amazon Corretto
e. Azul Zulu
DATA TYPES
In Java, data types are the foundation for defining variables and constants.
They determine the type of data that can be stored and the operations that
can be performed on that data. Java has two main categories of data types:
Primitive data types in Java are the most basic types of data. They are
predefined by the language and represent simple values like integers,
floating-point numbers, characters, and booleans. There are 8 primitive
data types in Java:
1.1. Byte
Example:
bytebyteValue=100;
1.2. Short
Example:
shortshortValue=10000;
1.3. Int
Size: 32 bits (4 bytes)
Default value: 0
Range: -2^31 to 2^31-1 (approximately -2.14 billion to 2.14 billion)
Use case: The most commonly used integer data type in Java for
numeric calculations.
Example:
intintValue=100000;
1.4. Long
Example:
longlongValue=10000000000L;
1.5. Float
Example:
floatfloatValue=3.14f;
1.6. Double
Example:
doubledoubleValue=3.14159;
1.7. Boolean
Example:
booleanisJavaFun=true;
1.8. Char
Example:
charletter='A';
Java ensures efficient memory allocation with its primitive types. For
example, int is more memory-efficient than long, and float consumes less
memory than double.
2. Reference (or Object) Data Types
Key Characteristics:
Example:
classDog {
String name;
int age;
voidbark() {
System.out.println("Woof!");
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
DogmyDog=newDog(); // Reference type to the Dog object
myDog.name = "Buddy";
myDog.age = 5;
myDog.bark(); // Outputs: Woof!
}
}
Arrays are objects in Java that hold multiple values of a specific data
type. The type of an array is defined by the type of its elements followed
by square brackets ([]).
Example:
The numbers array holds integers, and the names array holds
references to String objects.
Example:
interfaceAnimal {
voidsound();
}
classDogimplementsAnimal {
publicvoidsound() {
System.out.println("Bark");
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
Animalanimal=newDog(); // Reference type to Dog object
animal.sound(); // Outputs: Bark
}
}
Here, Animal is an interface, and the Dog class implements it. The
variable animal is of the reference type Animal, but it holds a
reference to a Dog object.
Example:
Stringmessage="Hello, World!";
Type casting allows you to convert one data type into another. There are
two types of type casting in Java:
INHERITANCE
Example:-
classAnimal {
String name;
voideat() {
System.out.println("This animal is eating.");
}
}
Example:-
Example:-
classDogextendsAnimal {
// Dog class inherits all fields and methods from Animal class.
}
Example:-
classDogextendsAnimal {
voideat() {
super.eat(); // Calls the eat method from the Animal class
System.out.println("The dog is eating.");
}
}
Types of Inheritance in Java
Example:-
classAnimal {
voideat() {
System.out.println("Animal eats.");
}
}
classDogextendsAnimal {
voidbark() {
System.out.println("Dog barks.");
}
}
Example:-
classAnimal {
voideat() {
System.out.println("Animal eats.");
}
}
classMammalextendsAnimal {
voidwalk() {
System.out.println("Mammal walks.");
}
}
classDogextendsMammal {
voidbark() {
System.out.println("Dog barks.");
}
}
In this case, Dog inherits from Mammal, and Mammal inherits from
Animal. The Dog class has access to all methods of Mammal and Animal.
Example:-
classAnimal {
voideat() {
System.out.println("Animal eats.");
}
}
classDogextendsAnimal {
voidbark() {
System.out.println("Dog barks.");
}
}
classCatextendsAnimal {
voidmeow() {
System.out.println("Cat meows.");
}
}
In this example, both Dog and Cat are subclasses of Animal. They inherit
the eat() method from the Animal class
Example:-
classAnimal {
voidsound() {
System.out.println("Animal makes a sound.");
}
}
classDogextendsAnimal {
@Override
voidsound() {
System.out.println("Dog barks.");
}
}
3. super() Constructor Call: A subclass can use super() to call
the superclass’s constructor explicitly. If no super() is called,
Java implicitly calls the no-argument constructor of the
superclass. The super() constructor call must be the first line
in the subclass's constructor.
Example:-
classAnimal {
Animal() {
System.out.println("Animal constructor.");
}
}
classDogextendsAnimal {
Dog() {
super(); // Calls the constructor of Animal class
System.out.println("Dog constructor.");
}
}
Example of Inheritance
Example:-
classVehicle {
int speed;
voidmove() {
System.out.println("Vehicle is moving at speed: " + speed);
}
}
classCarextendsVehicle {
int numDoors;
voiddisplay() {
System.out.println("Car has " + numDoors + " doors and is moving
at speed: " + speed);
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
CarmyCar=newCar();
myCar.speed = 60; // Inherited from Vehicle
myCar.numDoors = 4; // Specific to Car
myCar.move(); // Inherited method
myCar.display(); // Specific to Car
}
}
Explanation:
Vehicle is the superclass that has a speed attribute and a move()
method.
Car is the subclass that inherits speed and move() from Vehicle and
adds a numDoors attribute and a display() method.
The myCar object of class Car has access to both the Vehicle and
Car methods.
Advantages of Inheritance
Disadvantages of Inheritance
Example:-
finalclassAnimal {
// Cannot be inherited
}
classDogextendsAnimal { // This will result in a compilation error
}
POLYMORPHISM
Example:
classCalculator {
// Method for adding two integers
intadd(int a, int b) {
return a + b;
}
Java does not support operator overloading directly (unlike languages like
C++). The only exception is the + operator, which is overloaded to
perform both addition and string concatenation.
Example:
intsum=10 + 20;
// Addition of integersStringmessage="Hello " + "World!"; // String
concatenation
Example:
classAnimal {
voidsound() {
System.out.println("Animal makes a sound");
}
}
classDogextendsAnimal {
@Override
voidsound() {
System.out.println("Dog barks");
}
}
classCatextendsAnimal {
@Override
voidsound() {
System.out.println("Cat meows");
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
Animalanimal1=newDog(); // Upcasting
Animalanimal2=newCat(); // Upcasting
2.2 Upcasting
Example:
AnimalmyDog=newDog(); // Upcasting
myDog.sound(); // Calls the Dog class's overridden method
Example:
interfaceAnimal {
voidsound();
}
classDogimplementsAnimal {
publicvoidsound() {
System.out.println("Dog barks");
}
}
classCatimplementsAnimal {
publicvoidsound() {
System.out.println("Cat meows");
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
Animalanimal1=newDog();
Animalanimal2=newCat();
animal1.sound(); // Outputs: Dog barks
animal2.sound(); // Outputs: Cat meows
}
}
Here, Dog and Cat implement the Animal interface. Even though animal1
and animal2 are references of type Animal, the correct implementation of
the sound() method is chosen at runtime based on the actual type of the
object.
Advantages of Polymorphism
Disadvantages of Polymorphism
Summary