0% found this document useful (0 votes)
6 views29 pages

Unit 1 Java Notes

The document provides an overview of Java programming, covering its history, features, data types, operators, control statements, and object-oriented principles. It highlights Java's object-oriented nature, platform independence, and robustness, along with various data types and control structures like loops and conditionals. Additionally, it explains the importance of classes and objects in Java programming, emphasizing the foundational concepts of OOP.
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)
6 views29 pages

Unit 1 Java Notes

The document provides an overview of Java programming, covering its history, features, data types, operators, control statements, and object-oriented principles. It highlights Java's object-oriented nature, platform independence, and robustness, along with various data types and control structures like loops and conditionals. Additionally, it explains the importance of classes and objects in Java programming, emphasizing the foundational concepts of OOP.
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

JAVA PROGRAMMING

UNIT – I
Foundations of Java: History of Java, Java Features, Variables, Data Types, Operators, Expressions,
Control Statements. Elements of Java - Class, Object, Methods, Constructors and Access Modifiers,
Generics, Inner classes, String class and Annotations.
OOP Principles: Encapsulation – concept, setter and getter method usage, this keyword. Inheritance -
concept, Inheritance Types, super keyword. Polymorphism – concept, Method Overriding usage and
Type Casting. Abstraction – concept, abstract keyword and Interface.

History of Java:
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995.
Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as [Link], [Link], etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Java Features

 Object-Oriented (OOP): Java is a pure object-oriented language that organizes


programs around objects and classes. It supports key OOP concepts like abstraction,
encapsulation, inheritance, and polymorphism, which promotes modular and reusable
code.
 Platform Independent: Java is compiled into an intermediate form called bytecode,
which does not depend on a specific operating system or machine architecture. The
Java Virtual Machine (JVM) interprets this bytecode for the host machine, allowing a
program compiled on one platform (e.g., Windows) to run on another (e.g., Linux or
macOS).
 Simple: Java was designed to be easy to learn and use. It simplifies programming by
removing complex features found in languages like C/C++, such as explicit pointers,
operator overloading, and multiple inheritance.
 Robust: The language emphasizes early error checking at compile time and runtime
through a strong memory management system, automatic garbage collection, and
comprehensive exception handling.
 Secure: Java provides built-in security features, including running programs within a
virtual machine sandbox and using a bytecode verifier to check for illegal code. The
absence of pointers prevents direct memory access, mitigating security flaws like
buffer overflows.
 Multithreaded: Java supports multithreading, allowing multiple parts of a program
(threads) to run concurrently. This feature is essential for building interactive, high-
performance applications and maximizing CPU utilization.
 Portable: Being architecture-neutral and having a clean portability boundary makes
Java highly portable across different hardware and software environments.
 High Performance: While Java bytecode is interpreted by the JVM, it achieves high
performance through the use of a Just-In-Time (JIT) compiler, which translates
bytecode into native machine code during execution.
 Dynamic: Java is a dynamic language that can adapt to an evolving environment,
supporting the dynamic loading of classes and integration with native languages like
C and C++.
 Distributed: It provides extensive libraries (such as Remote Method Invocation
(RMI) and Enterprise Java Beans (EJB)) for creating distributed applications that can
communicate across networks.

Data Types
Java programming language has a rich set of data types. The data type is a category of data
stored in variables. In java, data types are classified into two types and they are as follows.
Primitive Data Types
Non-primitive Data Types
Primitive Data Types
Primitive data types are the basic building blocks of data manipulation in Java. They are
predefined and store simple values directly in memory. There are eight primitive types:
Data Type Size

byte 1 byte

short 2 bytes

int 4 bytes

long 8 bytes

float 4 bytes

double 8 bytes

boolean JVM-dependent

char 2 bytes

Non-Primitive (Reference) Data Types


Non-primitive data types are more complex and are user-defined (except for String). They
store references (memory addresses) to objects in the heap rather than the actual data values
directly in the stack.
 String: Represents a sequence of characters and is an immutable object in Java.
 Classes: User-defined blueprints that define methods and variables, forming the basis
of Object-Oriented Programming (OOP).
 Objects: Instances of a class that have state and behavior.
 Interfaces: Define a contract of abstract methods that implementing classes must
follow, allowing for abstraction and multiple inheritance.
 Arrays: Objects that store multiple elements of the same type in a single structure
with a fixed length.

Java operators
Java operators are special symbols used to perform operations on variables and values, such
as mathematical calculations, comparisons, and logical evaluations. They are categorized into
several groups, each serving a specific purpose.
The main types of operators in Java are:
 Arithmetic Operators: Used for performing basic mathematical operations.
o + (Addition), - (Subtraction), * (Multiplication), / (Division),
% (Modulus/Remainder)
Example 1: Arithmetic Operators
class Main {
public static void main(String[] args) {

// declare variables
int a = 12, b = 5;

// addition operator
[Link]("a + b = " + (a + b));

// subtraction operator
[Link]("a - b = " + (a - b));

// multiplication operator
[Link]("a * b = " + (a * b));

// division operator
[Link]("a / b = " + (a / b));

// modulo operator
[Link]("a % b = " + (a % b));
}
}


Increment and Decrement Operators
o ++ (Increment, increases value by 1)
o -- (Decrement, decreases value by 1)
class Main {
public static void main(String[] args) {

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
[Link]("Value of a: " + a);

// increment operator
result1 = ++a;
[Link]("After increment: " + result1);

[Link]("Value of b: " + b);

// decrement operator
result2 = --b;
[Link]("After decrement: " + result2);
}
}
 Assignment Operators: Used to assign values to variables. The simple assignment
operator is =, but compound operators provide a shorthand for combining an
arithmetic operation with assignment (e.g., += is equivalent to a = a + 3).

Relational (Comparison) Operators: Used to compare two values and return a



boolean result (true or false).
o == (Equal to)
o != (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
class Main {
public static void main(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b
[Link]("a is " + a + " and b is " + b);

// == operator
[Link](a == b); // false

// != operator
[Link](a != b); // true

// > operator
[Link](a > b); // false

// < operator
[Link](a < b); // true

// >= operator
[Link](a >= b); // false

// <= operator
[Link](a <= b); // true
}
}

Logical Operators: Used to combine multiple boolean conditions.



o && (Logical AND, true if both conditions are true)
o || (Logical OR, true if at least one condition is true)
o ! (Logical NOT, reverses the boolean result)
class Main {
public static void main(String[] args) {

// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false

// || operator
[Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
[Link]((5 < 3) || (8 < 5)); // false

// ! operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}

 Bitwise Operators: Perform operations on individual bits of integer data types.


o & (Bitwise AND)
o | (Bitwise OR)
o ^ (Bitwise XOR)
o ~ (Bitwise Complement)
o << (Left Shift)
o >> (Signed Right Shift)
o >>> (Unsigned Right Shift/Zero fill right shift)

public class BitwiseOperators


{
public static void main(String[] args)
{
int a = 25, b = 20;
[Link](a + " & " + b + " = " + (a & b));
[Link](a + " | " + b + " = " + (a | b));
[Link](a + " ^ " + b + " = " + (a ^ b));
[Link]("~" + a + " = " + ~a);
[Link](a + ">>" + 2 + " = " + (a>>2));
[Link](a + "<<" + 2 + " = " + (a<<2));
[Link](a + ">>>" + 2 + " = " + (a>>>2));
}
}

 Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
Here's how it works.
 If the Expression is true, expression1 is assigned to the variable.
 If the Expression is false, expression2 is assigned to the variable.
Public class Java
{
public static void main(String[] args)
{

int februaryDays = 29;


String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
[Link](result);
}
}

Control Statements

Control statements in Java allow you to control the flow of your program, make
decisions, and repeat tasks.

Simple if Statement:
The 'if' statement is used to execute a block of code only if a specified condition
is 'true'. It's one of the most fundamental control structures in Java.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}

Example:
int age = 18;
if (age >= 18)
{
[Link]("You are an adult.");
}

In this example, the code inside the 'if' block is executed because the condition 'age
>= 18' is 'true'.

if-else Statement:
The 'if-else' statement is used to execute one block of code if a condition is 'true' and
another block if the condition is 'false'.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}

Example:
int age = 15;
if (age >= 18) {
[Link]("You are an adult.");
}
else {
[Link]("You are not yet an adult.");
}

In this example, the second '[Link]' statement is executed because the


condition 'age >= 18'is 'false'.

Nested if else:

A nested if statement in Java is an if statement placed inside the block of


another if or else statement. This allows you to handle complex decision-making
scenarios where a secondary condition must be checked only after a primary condition
has been met.

Syntax
if (condition1) {
// Code to be executed if condition1 is true

if (condition2) {
// Code to be executed if both condition1 and condition2 are true
} else {
// Code to be executed if condition1 is true, but condition2 is false
}
} else {
// Code to be executed if condition1 is false
}

Example:

public class Example3


{
public static void main(String[] args)
{
int n;
n=10;
if(n>=0)
{
if(n>=20)
{
[Link]("n is greater than 20");
}
else
{
[Link]("n is less than 20");
}
}
else
{
[Link]("n is less than zero");
}
}
}

else if statement:

Syntax

if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// Code to execute if condition1 and condition2 are false, and condition3 is true
} else {
// Code to execute if none of the conditions are true (optional)
}

Example:
public class Example4
{
public static void main(String[]args)
{
int marks;
marks=80;
if (marks>=90)
{
[Link]("grade is O");
}
else if(marks>=80&&marks<90)
{
[Link]("grade is A");
}
else if(marks>=70&&marks<80)
{
[Link]("grade is B");
}
else if(marks>=60&&marks<70)
{
[Link]("grade is C");
}
else
{
[Link]("grade is D");
}
}
}

'switch' Statement:
The 'switch' statement is used for multiple branches of execution based on the value
of an expression. It's an alternative to using multiple 'if-else' statements.
Syntax:
switch (expression)
{
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// ...
default:
// Code to execute if expression doesn't match any case
}

Example:
int dayofWeek = 3;
switch (dayofWeek)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
// ...
default:
[Link]("Invalid day");
}

Loops:
Loops in Java allow you to execute a block of code repeatedly. Java provides several
types of loops:
1. for Loop:
for loop is used when you know in advance how many times you want to execute a
block of code.
Syntax:
for (initialization; condition; iteration)
{
// Code to execute repeatedly
}

Example:
for (int i = 1; i <= 5; i++) {
[Link]("Iteration " + i);
}

This 'for' loop will execute the code block five times, printing "Iteration 1" through
"Iteration 5."
2. while Loop:
while loop is used when you want to execute a block of code as long as a certain
condition is 'true'.
Syntax:
while (condition)
{
// Code to execute repeatedly
}

Example:
int count = 0;
while (count < 3) {
[Link]("Count: " + count);
count++;
}

This 'while' loop will execute the code block three times, printing "Count: 0," "Count:
1," and "Count: 2."
3. do-while Loop:
do-while' loop is similar to the 'while' loop, but it always executes the code block at
least once, even if the condition is initially false.
Syntax:

do {
// Code to execute repeatedly
} while (condition);

Example:
int i = 1;
do {
[Link]("Iteration " + i);
i++;
} while (i <= 3);

This 'do-while' loop will execute the code block three times, printing "Iteration 1,"
"Iteration 2," and "Iteration 3."

Classes and Objects


Classes and objects are fundamental concepts in object-oriented programming (OOP).
Java is an object-oriented language, and understanding classes and objects is essential
for writing Java programs. In this Core Java tutorial, we'll explore classes and objects
in detail, along with comprehensive explanations and examples.
1. Class:
A class is a blueprint or template for creating objects. It defines the structure and
behaviour of objects. In Java, a class is declared using the class keyword.
Syntax:
public class ClassName
{
// Fields (attributes or properties)
dataType fieldName1;
dataType fieldName2;
// ...

// Constructors
public ClassName()
{
// Constructor code
}

// Methods (functions)
returnType methodName1(parameterType1 param1, parameterType2 param2, ...)
{
// Method code
}

returnType methodName2(parameterType1 param1, parameterType2 param2, ...)


{
// Method code
}

// ...
}

 'public class ClassName' : Declares a class with the name 'ClassName'.


The 'public' keyword makes the class accessible from other classes.
 Fields: These are attributes or properties that define the state of objects created from
the class.
 Constructors: Special methods used to initialize objects of the class.
 Methods: Functions that define the behavior of objects created from the class.
Example:
Let's create a simple class called 'Person' :
public class Person {
// Fields
String name;
int age;

// Constructor
public Person(String n, int a) {
name = n;
age = a;
}

// Method to display information


public void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
Copy to Clipboard

2. Object:
An object is an instance of a class. It represents a real-world entity and has its own
state and behavior. To create an object, you use the 'new' keyword followed by a
constructor of the class.
Syntax:
ClassName objectName = new ClassName();
Copy to Clipboard

 'ClassName': The name of the class.


 'objectName': The name you give to the object.
 'new': The keyword used to create an instance of the class.
 'ClassName()': The constructor of the class used to initialize the object.
Example:
Let's create two 'Person' objects:
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);

// Call methods on objects


[Link]();
[Link]();
Copy to Clipboard

In this example, we created two 'Person' objects, 'person1' and 'person2', and called
the 'displayInfo' method on each object to display their information.

3. Constructors:
Constructors are special methods used to initialize objects when they are created.
They have the same name as the class and do not have a return type.
Example:
public class Student {
String name;
int age;

// Constructor
public Student(String n, int a) {
name = n;
age = a;
}

public void displayInfo() {


[Link]("Name: " + name);
[Link]("Age: " + age);
}
}

In this example, the 'Student' class has a constructor that takes two
parameters, 'name'and 'age', to initialize the object's state when it's created.

4. Methods:
Methods define the behavior of objects created from a class. They are functions that
can perform actions and return values.
Example:
public class Circle {
double radius;

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

// Method to calculate area


public double calculateArea() {
return [Link] * radius * radius;
}
}

In this example, the 'Circle'class has a method 'calculateArea'that calculates and


returns the area of the circle.

Access Modifiers
In Java, access modifiers are keywords used to set the accessibility (scope) of classes,
interfaces, variables, methods, and constructors. They control which other parts of the
code can access a particular member, enforcing encapsulation and security.
 public: This provides the widest scope. Anything declared public can be accessed
from any other class, in any package.
 protected: This level is more restrictive than public but less than default. It is
typically used with inheritance to allow subclasses to access specific members of a
parent class.
 default (package-private): When no access modifier is specified, the member or
class has default access. It is only visible to classes within the same package.
 private: This is the most restrictive level. Members declared private are only visible
within the class where they are declared.

Inner Class:
An inner class is a class declared inside the body of another class. The inner class has
access to all members (including private) of the outer class, but the outer class can
access the inner class members only through an object of the inner class.

Syntax:
class OuterClass {
// Outer class members

class InnerClass {
// Inner class members
}

Example:

public class OuterClass {

class InnerClass {
void display() {
[Link]("Hello from Inner Class!");
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
InnerClass inner = [Link] InnerClass();
[Link]();
}
}

Features of Inner Classes


 Encapsulation: Inner classes can access private members of the outer class,
providing better encapsulation.
 Code Organization: Logically groups classes that belong together, making code
more readable.
 Access to Outer Class: Inner class instances have a reference to the outer class
instance.
 Namespace Management: Helps avoid naming conflicts by nesting related classes.

String Class in Java


The String class in Java is used to create and manipulate sequences of characters. It is one of
the most commonly used classes in Java. Objects of the String class are immutable, which
means they cannot be changed once created.
Key Features of the String Class
1. Immutable
Immutable means that once a String object is created, its value cannot be changed.
Example:
public class Main {
public static void main(String[] args) {
String text = "hello";
[Link](0) = 'H'; // compile-time error
}
}
Explanation: The line [Link](0) = 'H'; causes a compile-time error because charAt(0)
returns a read-only char, not a variable. String is immutable in Java, you cannot modify its
characters directly.
2. Thread-Safe
String in Java is thread-safe because it is immutable, allowing safe access by multiple threads
without synchronization.
3. Supports Various Utility Methods
String is a predefined final class in Java present in [Link] package. It provides various
methods to create, manipulate, and compare strings, like length(), charAt(), concat(), equals(),
etc.
import [Link].*;

class GFG {
public static void main (String[] args) {
String str = "hello geeks";
[Link]("Length of String-> "+[Link]());
[Link]("Changed String ->"+[Link]());
}
}

Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
 declare class variables/attributes as private
 provide public get and set methods to access and update the value of
a private variable
Get and Set methods
You learned from the previous chapter that private variables can only be accessed within the
same class (an outside class has no access to it). However, it is possible to access them if we
provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable,
with the first letter in upper case:
Example
public class Person {
private String name; // private = restricted access

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

// Setter
public void setName(String newName) {
[Link] = newName;
}
}
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable.
this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this
class:

this Keyword
this keyword in Java refers to the current object in a method or constructor.
this keyword is often used to avoid confusion when class attributes have the same name as
method or constructor parameters.

Accessing Class Attributes


Sometimes a constructor or method has a parameter with the same name as a class variable.
When this happens, the parameter temporarily hides the class variable inside that method or
constructor.
To refer to the class variable and not the parameter, you can use the this keyword:
Example
public class Main {
int x; // Class variable x
// Constructor with one parameter x
public Main(int x) {
this.x = x; // refers to the class variable x
}

public static void main(String[] args) {


// Create an object of Main and pass the value 5 to the constructor
Main myObj = new Main(5);
[Link]("Value of x = " + myObj.x);
}
}
Output:
Value of x = 5

Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another. We group
the "inheritance concept" into two categories:
 subclass (child) - the class that inherits from another class
 superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):

class Vehicle
{
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

// Call the honk() method (from the Vehicle class) on the myCar object
[Link]();

// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
[Link]([Link] + " " + [Link]);
}
}
Types of Inheritance in Java
Below are the different types of inheritance which are supported by Java.
 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
 Hybrid Inheritance

1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.
Single Inheritance
//Super class
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}

// Subclass
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}

public class Test {


public static void main(String[] args) {
// Creating object of subclass invokes base class constructor
Car obj = new Car();
}
}

Output
This is a Vehicle
This Vehicle is Car

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also acts as the base class for other classes.
Multilevel Inheritance
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
class FourWheeler extends Vehicle {
FourWheeler() {
[Link]("4 Wheeler Vehicles");
}
}
class Car extends FourWheeler {
Car() {
[Link]("This 4 Wheeler Vehicle is a Car");
}
}
public class Geeks {
public static void main(String[] args) {
Car obj = new Car(); // Triggers all constructors in order
}
}

Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehicle is a Car

3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e.
more than one derived class is created from a single base class. For example, cars and buses
both are vehicle
Hierarchical Inheritance
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}

class Car extends Vehicle {


Car() {
[Link]("This Vehicle is Car");
}
}
class Bus extends Vehicle {
Bus() {
[Link]("This Vehicle is Bus");
}
}

public class Test {


public static void main(String[] args) {
Car obj1 = new Car();
Bus obj2 = new Bus();
}
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit features
from all parent classes.
Note: that Java does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces.
Multiple Inheritance
interface LandVehicle {
default void landInfo() {
[Link]("This is a LandVehicle");
}
}
interface WaterVehicle {
default void waterInfo() {
[Link]("This is a WaterVehicle");
}
}
// Subclass implementing both interfaces
class AmphibiousVehicle implements LandVehicle, WaterVehicle {
AmphibiousVehicle() {
[Link]("This is an AmphibiousVehicle");
}
}
public class Test {
public static void main(String[] args) {
AmphibiousVehicle obj = new AmphibiousVehicle();
[Link]();
[Link]();
}
}

Output
This is an AmphibiousVehicle
This is a WaterVehicle
This is a LandVehicle

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to implement
Hybrid inheritance.
Hybrid Inheritance
Explanation:
 class Car extends Vehicle->Single Inheritance
 class Bus extends Vehicle and class Bus implements Interface Fare->Hybrid
Inheritance (since Bus inherits from two sources, forming a combination of single +
multiple inheritance).

IS-A type of Relationship:


IS-A represents an inheritance relationship in Java, meaning this object is a type of that
object.
public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}
Now, based on the above example, in Object-Oriented terms, the following are true:
 SolarSystem is the superclass of Earth class.
 SolarSystem is the superclass of Mars class.
 Earth and Mars are subclasses of SolarSystem class.
 Moon is the subclass of both Earth and SolarSystem classes.

class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

[Link](s instanceof SolarSystem);


[Link](e instanceof Earth);
[Link](m instanceof SolarSystem);
}
}

What Can Be Done in a Subclass?


In sub-classes we can inherit members as is, replace them, hide them or supplement them
with new members:
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in the example above, toString() method is
overridden).
 We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the superclass.
 We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.
Advantages of Inheritance in Java
 Code Reusability: Inheritance allows for code reuse and reduces the amount of code
that needs to be written. The subclass can reuse the properties and methods of the
superclass, reducing duplication of code.
 Abstraction: Inheritance allows for the creation of abstract classes that define a
common interface for a group of related classes. This promotes abstraction and
encapsulation, making the code easier to maintain and extend.
 Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can
be used to model real-world objects and their relationships.
 Polymorphism: Inheritance allows for polymorphism, which is the ability of an
object to take on multiple forms. Subclasses can override the methods of the
superclass, which allows them to change their behavior in different ways.

super Keyword
In Java, the super keyword is used to refer to the parent class of a subclass.
The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
It can be used in two main ways:
 To access attributes and methods from the parent class
 To call the parent class constructor

Access Parent Methods


If a subclass has a method with the same name as one in its parent class, you can use super to
call the parent version:
Example
class Animal {
public void animalSound() {
[Link]("The animal makes a sound");
}
}

class Dog extends Animal {


public void animalSound() {
[Link](); // Call the parent method
[Link]("The dog says: bow wow");
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
[Link]();
}
}
Output:
The animal makes a sound
The dog says: bow wow

Polymorphism:
Polymorphism in Java is one of the core concepts in object-oriented programming
(OOP) that allows objects to behave differently based on their specific class type. The
word polymorphism means having many forms, and it comes from the Greek words poly
(many) and morph (forms), this means one entity can take many forms. In Java,
polymorphism allows the same method or object to behave differently based on the context,
specially on the project's actual runtime class.
Features of polymorphism:
 Multiple Behaviors: The same method can behave differently depending on the
object that calls this method.
 Method Overriding: A child class can redefine a method of its parent class.
 Method Overloading: We can define multiple methods with the same name but
different parameters.
 Runtime Decision: At runtime, Java determines which method to call depending on
the object's actual class.
Types of Polymorphism in Java
In Java Polymorphism is mainly divided into two types:
Types of Polymorphism in Java

1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java is also known as static polymorphism and also known
as method overloading. This happens when multiple methods in the same class have the
same name but different parameters.
Note: But Java doesn't support the Operator Overloading.
Method Overloading
As we discussed above. Method overloading in Java means when there are multiple
functions with the same name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by changes in the number of arguments or/and a
change in the type of arguments.
Example: Method overloading by changing the number of arguments
// Class 1
// Helper class
class Helper {

// Method with 2 integer parameters


static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}

// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}

// Class 2
// Main class
class Geeks
{
// Main driver method
public static void main(String[] args) {

// Calling method by passing


// input as in arguments
[Link]([Link](2, 4));
[Link]([Link](5.5, 6.3));
}
}

Output
8
34.65

Explanation: The Multiply method is overloaded with different parameter types. The
compiler picks the correct method during compile time based on the arguments.

2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in
which a function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. Method overriding, on the other hand,
occurs when a derived class has a definition for one of the member functions of the base
class. That base function is said to be overridden.

Method Overriding
Method overriding in Java means when a subclass provides a specific implementation of a
method that is already defined in its superclass. The method in the subclass must have the
same name, return type, and parameters as the method in the superclass. Method overriding
allows a subclass to modify or extend the behavior of an existing method in the parent
class. This enables dynamic method dispatch, where the method that gets executed is
determined at runtime based on the object's actual type.
Example: This program demonstrates method overriding in Java, where the Print() method
is redefined in the subclasses (subclass1 and subclass2) to provide specific
implementations.
// Class 1
// Helper class
class Parent {

// Method of parent class


void Print() {
[Link]("parent class");
}
}

// Class 2
// Helper class
class subclass1 extends Parent {

// Method
void Print() {
[Link]("subclass1");
}
}

// Class 3
// Helper class
class subclass2 extends Parent {

// Method
void Print() {
[Link]("subclass2");
}
}

// Class 4
// Main class
class Geeks {

// Main driver method


public static void main(String[] args) {
// Creating object of class 1
Parent a;

// Now we will be calling print methods


// inside main() method
a = new subclass1();
[Link]();

a = new subclass2();
[Link]();
}
}

Output
subclass1
subclass2

abstract keyword:
Java Abstract Class
The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes).
We use the abstract keyword to declare an abstract class. For example,
// create an abstract class
abstract class Language {
// fields and methods
}
...

// try to create an object Language


// throws an error
Language obj = new Language();
An abstract class can have both the regular methods and abstract methods. For example,
abstract class Language {

// abstract method
abstract void method1();

// regular method
void method2() {
[Link]("This is regular method");
}
}
To know about the non-abstract methods, visit Java methods. Here, we will learn about
abstract methods.

Java Abstract Method


A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods. For example,
abstract void display();
Here, display() is an abstract method. The body of display() is replaced by ;.
If a class contains an abstract method, then the class should be declared abstract. Otherwise, it
will generate an error. For example,
// error
// class should be abstract
class Language {

// abstract method
abstract void method1();
}

Example: Java Abstract Class and Method


Though abstract classes cannot be instantiated, we can create subclasses from it. We can then
access members of the abstract class using the object of the subclass. For example,

abstract class Language {

// method of abstract class


public void display() {
[Link]("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
[Link]();
}
}

Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}

To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface


class Pig implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
[Link]("The pig says: wee wee");
}
public void sleep() {
// The body of sleep() is provided here
[Link]("Zzz");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();
[Link]();
}
}

*********

You might also like