JAVA Notes _ JBDL 76_Noida 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Types of Applications:

Standalone Application:
Java Standalone Application” does not require the Internet. It runs on a local machine. It
takes its input from the local machine as well as saves its data to that local machine.
Ex. Calculator app and notepad, word etc

Web Applications:
The main purpose of web application is to generate dynamic response from server
machine.Web application provides services to web clients only(using the browser we
need to send the request).
Java:

1-Platform Independence:
2-Object-Oriented:
3-Memory Management:
4-Strongly Typed:
5-Multi-Threading Support:
6-Security:

Platform Independent (WORA) feature of java:

The most unique feature of java is platform independent. In any programming language
source code is compiled into executable code . This cannot be run across all platforms.
When javac compiles a java program it generates an executable file called .class
file.This class file contains byte codes. Byte codes are interpreted only by JVM’s . Since
these JVM’s are made available across all platforms by Sun Microsystems, we can
execute this byte code in any platform. Byte code generated in the Windows
environment can also be executed in the Linux environment. This makes the java
platform independent.
JAVA Architecture:
● JDK is for Java development and includes the tools needed for compiling and
developing Java applications.
● JRE is for end-users and includes the JVM and libraries for running Java
applications.
● JVM executes Java bytecode and provides a runtime environment for Java
applications.
● JIT is a part of the JVM and improves the performance of Java applications by
compiling bytecode into native machine code at runtime.

OOP’s :Object-Oriented Programming


● Think of objects as real-world things like a car, dog, or phone. Each object has its own
properties (like a car's color, speed) and behaviors (like a car can start, stop).
Class:
A class is a kind of blueprint or template for objects. Class defines variables,
methods. A class tells what type of objects we are creating.
For example, if you have a blueprint for a car, it tells you what features (like wheels,
color) and behaviors (like driving, braking) a car should have.
E.g.
public class FirstClass
{public static void main(String[] args)
{System.out.println(“My First class”);}}

Object:
An Object is an instance of class. A class defines a type of object. Each object
belongs to some class. Every object contains state and behavior. State is determined by
value of attributes and behavior is called method. Objects are also called as an
instance. Example:

● Class: Blueprint for a car (it defines that all cars have wheels, doors, and can
start/stop).
● Object: A specific car (like your red Toyota) made using that blueprint.

Memory Management of Java:


● Stack Memory : Short lived and method specific values are kept inside it.
● Heap Memory: Dynamic memory allocation for objects at run time.
● Meta Space Memory: Memory for class metaData.(static block print)
Garbage Collector:
When you create objects in Java using the new keyword, memory is allocated for those
objects on the heap. The heap is the part of the memory used for dynamic memory
allocation. The garbage collector identifies objects that are no longer reachable or
referenced by the program. An object is considered reachable if there is at least one
reference pointing to it.

Constructors:
A constructor is a special method used to initialize objects. It is called
automatically when an object is created.
● No argument constructor
● Parameterized constructor
Example:

Constructor Chaining:(this keyword)

Access Modifiers:
(explain with example)
Below are the modifiers for classes, attributes, methods and constructors:
Modifiers Description

public That code can be accessed from anywhere in the code

protected That code can be accessed from within the declared


same package or subclass from some outside
package

private That code can be accessed from within the declared


class

default(package-privat That code can be accessed from within the same


e) declared package
Access Levels:
Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

default Y Y N N
(no modifier)

private Y N N N

Encapsulation
In simple terms is the concept of wrapping data (variables) and the methods (functions)
that operate on the data into a single unit, which is typically a class in object-oriented
programming.

Wrapping the code into a single unit to provide you the control over data. We can make
read-only and write-only classes with this. Easy to test, can add custom functionalities
while getting and setting the data.

To achieve encapsulation:
To make private variables and public getter setters to access and update the values.

Data Hiding: It restricts direct access to some of the object's components, meaning that
the internal details (data) are hidden from outside the class. Instead, you interact with
the object's data through public methods.

Control Access: You control how the data is modified or accessed by providing
methods (getters and setters) that manage the data, which helps protect the data from
unintended or harmful changes.
Advantages of Encapsulation:

a. We can achieve security.


b. Enhancement becomes easy.
c. Maintainability and modularisation becomes easy.
d. It provides flexibility to the user to use the system very easily.

Inheritance:
● One class can inherit the features and behaviors of another class.
● Inheriting is the process of acquiring features of others.
● For example a child acquires the features of their parents.
● In java inheritance is the process of inheriting members of existing classes by
extending their functionality.
● We use extends keyword in java to extend a class in java.
● All java classes extend java.lang.Object since object class is the super class for
all classes in java.
● It always speaks about reusability.

SuperClass: Parent class/Base class from which features and behaviors are getting
inherited.
SubClass: Child class/Extended class/ Derived class which is inheriting the parent
class. It can have other functionalities as well.

Features of Inheritance in JAVA:


● Default SuperClass : object class is superclass to everything.
● SuperClass can only be one : due to multiple inheritance not allowed, can have
only one superclass.
● Inheriting constructor : constructors do not get inherited but can be called via
subclass constructor.
● Private member inheritance : child class does not inherit private members of
parent class.

Inheritance Rules in Java:

1. Parent Class Members Availability:


○ All members (fields and methods) of the parent class are inherited and available
to the child class by default.
2. Child Class Members Availability:
○ The members of the child class are not available to the parent class by default.
3. Calling Methods on References:
○ Using a child class reference, you can access both parent class and child
class methods.

// Using Child reference Child child = new Child();

○ Using a parent class reference, you can only call parent class methods, even if
the reference holds a child class object.

// Using Parent reference Parent parent = new Parent();

// Using Parent reference Parent parent = new Child();

4. Object Reference Assignments:


○ A child class object can be referenced by a parent class reference
(upcasting). //Parent parent = new Child(). Upcasting :
○ A parent class object cannot be referenced by a child class reference
(downcasting without an explicit cast will cause a compile-time error).

Child childRef = new Parent(); // Compile-time error: Incompatible types }Downcasting :


ChildClass c= (ChildClass) new ParentClass();// possible Downcasting :

Types of Inheritance in JAVA:


1. Single Inheritance: A subclass inherits from one superclass.
● Example: class Dog extends Animal
2. Multilevel Inheritance: A class is derived from a subclass, creating a chain.
● Example: class Puppy extends Dog extends Animal
3. Hierarchical Inheritance: Multiple subclasses inherit from one superclass.
● Example: class Cat extends Animal, class Dog extends Animal
4. Hybrid Inheritance: A combination of two or more types of inheritance.
5. Multiple Inheritance (via Interface): A class implements multiple interfaces.
● Example: class Dog implements Animal, Pet
Super Keyword:
● Refers to the parent class (superclass) object.
● Used to access parent class methods, variables, or constructors.
● Provide constructor chaining in parent to child classes.
● Example

This Keyword:

● Refers to the current object of the class.


● Used to access instance variables, methods, or constructors within the same
class.
● this() is used for calling the current class constructor,
● This is used for referring to the current class variable .
● Example:
Polymorphism:
● Polymorphism means the ability to take many forms.
● In Java, polymorphism allows one interface or method to be used for different
types of objects.

OVERLOADING:
● COMPILE TIME / OVERLOADING/ EARLY BINDING POLYMORPHISM
● Two or more methods are said to be Overloaded if both methods have the same
name but change in the argument type.
● Do not depend upon the return type.

Eg:: abs(int)
abs(float)
abs(long)

Rules of Method Overloading in Java:

1. Same Method Name:


○ All overloaded methods must have the same name but different
parameter lists.
2. Different Parameter List (Signature):
○ The parameter list of each overloaded method must be different in at
least one of the following:
■ Number of parameters (e.g., method(int) and method(int,
int)).
■ Type of parameters (e.g., method(int) and method(double)).
■ Order of parameters if types differ (e.g., method(int, double)
and method(double, int)).
3. Return Type Does Not Matter:
○ The return type cannot be used to distinguish overloaded methods.
Changing only the return type will result in a compilation error.
4. Access Modifiers and Exception Handling:
○ Overloaded methods can have different access modifiers (e.g.,
public, private, protected).
○ They can also throw different exceptions or none at all.
5. Static and Instance Methods:
○ Overloading is possible for both static and instance methods. You can
overload a static method with another static or instance method.
Run-time Polymorphism (Method Overriding):
● Achieved by overriding a method in a subclass.
● The method that gets called is determined at runtime, depending on the object
type.
● The parent class method which is overridden is called "Overridden method".
● The child class method which is overriding is called "Overriding method".

Polymorphism in Java is primarily achieved through method overriding. Method


overriding occurs when a subclass provides a specific implementation of a method that
is already defined in its superclass. The overridden method in the subclass should have
the same name, return type, and parameters as the method in the superclass.
When you call the method on an object of the subclass, the overridden method in the
subclass is executed.

Example:
class Animal {
void makeSound() {
System.out.println("generic sound of animal");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks");
}
}
// upcasting --> means when child object try to store in parent reference(possible)

// Parent p= new Child();

it prints the override value of child class because binding happens at run time which child class
object

—---------------------------------------------------

//Down casting --> means when parent class object try to store in child class reference

// 1--> Trying to Down casting Implicitly: Child c = new Parent(); - > compile time error

//2-->Down casting Explicitly: Child c = (Child)p; or Cat cat1= (Cat) new Animal();

// Cat cat1= (Cat) new Animal();// this results the class cast exception

/*

* You must ensure that the object you are casting (animal) is actually an instance of the

* child class (Cat), otherwise a ClassCastException will be thrown.

* example:

* Animal animal1= new Cat();

Cat cat1=(Cat) animal1

* */

Scenario 1::
Private methods are not visible in the Child classes hence the overriding concept is not
applicable for private methods.Based on our own requirement we can declare the same
Parent class private method in child class also. It is valid but not overriding.

Scenario 2::
If the method is declared as final in parent class then those methods we cannot override
in child class,it would result in a compile time error.

Scenario 3::
we can't override static method as instance method, it would result in compile time error.

Scenario 4::
we can't override instance(NON- STATIC) method as static,it would result in compile
time error
Rules with respect to scope
While Overriding we cannot reduce the scope of access modifier
eg1:: class Parent{public void methodOne(){}}
class Child extends Parent{protected void methodOne(){}}//Compile time error
Note
public => public
protected => protected/public
default => default/protected/public
private => Overriding concept is not applicable

Difference b/w method Overriding and method hiding?

Overriding => In both parent and child class method should be instance
Method resolution is based on a runtime object.
JVM will take the call so it is called as runtime polymorphism/dynamic dispatch.

Hiding => In both parent and child class methods should be static.
Method resolution is based on reference type.
Compiler will take the call so it is called Compile time polymorphism.
Method Overloading and Method Overriding in Java:

Feature Overloading Overriding

Method Name Same Same

Argument Type Must be different Must be the same

Method Same Same


Signature

Return Type No restrictions Same or covariant type

Access Modifier No restrictions Same or increased scope (private,


default, protected, public)

Private, Final Can be overloaded Cannot be overridden


Methods

Static Methods Can be overloaded Cannot be overridden (method hiding


occurs)

Throws Clause No restrictions If the child class throws an exception,


(Exceptions) the parent must throw the same or its
parent exception (applies to checked
exceptions only)

Binding Compile-time (static) Run-time (dynamic)

Alternative Compile-time binding / Run-time polymorphism / Late binding /


Name Early binding / Eager Lazy binding / Dynamic dispatch
binding / Static binding
Abstraction:
Hiding internal implementation and exposing the set of services is called "abstraction".
In java to promote abstraction we use "abstract class"/"interface".

Example:
1. By using ATM,GUI screen bank people are highlighting a set of services that they are
offering without highlighting internal implementation.

Advantages of Abstraction

a. Enhances security by hiding internal implementation.


b. Simplifies enhancements without affecting end users.
c. Increases flexibility for easy system use.
d. Improves application maintainability and modularity.
e. Enhances user experience by simplifying system interaction.

Abstract Class:
Instantiation of abstract class is not possible. Due to incomplete implementation.

Abstract Modifier
It is the modifier applicable only for methods and class but not for variables.

Abstract Methods
Even though we don't have implementation still we can declare a method with an abstract
modifier. That is abstract methods have only declaration but not implementation.
Example-
public abstract void methodOne(); => valid
public abstract void methodOne(){} => Invalid

abstract class Bank {


public abstract void deposit(double amount);
public abstract void withdraw(double amount);
// Common functionality
public void checkBalance()
{ System.out.println("Checking balance..."); }
Rules of Abstract class

● If a class contains at least one abstract method, make that class also abstract.
● Even if the class does not contain any abstract method still the class can be
made as abstract.
eg:: HttpServlet is an abstract class,but it does not contain abstract methods.

Can abstract classes have constructors?


An abstract class in Java can't be instantiated because it represents incomplete
functionality with abstract methods. Its constructor is used by subclasses to initialize
common fields, but only fully implemented subclasses can be instantiated.

What is the difference b/w final and abstract?


Example

final class A{
public abstract void methodOne();//Invalid
}

abstract class A{
public final void methodOne(){...}//Valid
}

Interface:
An interface in Java is a blueprint for a class that defines a contract of methods that a
class must implement, but without providing any concrete implementations. It contains
abstract methods (methods without a body) and constants.

Interface corresponds to service requirement specification or contract b/w client


and service provider or 100% pure abstract class till before java 8 .After static and
default implementation in java 8, interface is also not able to fulfill the criteria of
abstraction.

Interface Methods
● Every method present inside the interface is public.
● Every method present inside the method is abstract.
Interface variables
● Inside the interface we can define variables.
● Inside the interface variables define requirement level constants.
● Every variable present inside the interface is by default public ,static, and final.

Does the interface have a constructor?

Difference b/w extends vs implements (with example)


1.
● extends :: One class can extends only class at a time
● implements:: One class can implement any no of interface at a time.

2. A class can extend a class and can implement any no of interfaces simultaneously.
3. An interface can extend any number of the interfaces at a time.

In Java, you can provide an implementation inside an interface using default and
static methods, starting from Java 8. Here's how to do it:

1. Default Methods:
You can define a default method inside an interface, and it will have a default
implementation that can be used by classes implementing the interface. Here's an
example:
default void defaultMethod() {
System.out.println("This is a default method.");
}

The `defaultMethod` will be inherited from the interface, but the implementing class can
also override it if needed.

2. Static Methods:
You can also define static methods inside an interface, which are not inherited by
implementing classes. They can only be called using the interface name.
static void staticMethod() {
System.out.println("This is a static method.");
}
Differences between an Abstract Class and an Interface:

Feature Interface Abstract Class

Purpose Used when only the requirements Used when some implementation
(specifications) are known, and no is provided but not complete,
implementation details are leaving room for further
provided. subclassing.

Method Types All methods are public Methods can be abstract or


and
abstract by default (except for concrete (with or without an
default and static methods in Java implementation).
8+).

Method Modifiers Cannot use private, protected, No restrictions on method


final, static, synchronized, modifiers; can use private,
native, or strictfp on protected, final, etc.
methods.

Variables All variables are public, static, Variables can be of any type; no
and final by default. restrictions on modifiers.

Variable Cannot use private, protected, No restrictions on variable


Modifiers transient, or volatile for modifiers.
variables.

Variable Variables must be initialized at the No requirement for variable


Initialization time of declaration. initialization during declaration.

Blocks Static and instance blocks are not Can contain static and instance
allowed. blocks.

Constructor Cannot define a constructor. Can define a constructor to


initialize the abstract class.

Multiple A class can implement multiple A class can inherit from only one
Inheritance interfaces, allowing multiple abstract class due to single
inheritance of behavior. inheritance in Java.

Default and Static Can define default and static Methods can be concrete, but
Methods (Java methods with implementations. there are no default methods.
8+)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy