Java Unit-1
Java Unit-1
1.Introduction to java:
What is Java
Java is a high Level programming language and it is also called as a platform. Java is a
secured and robust high level object-oriented programming language. Platform: Any software
or hardware environment in which a program runs is known as a platform. Java has its own
runtime environment (JRE) and API so java is also called as platform. Java fallows the
concept of Write Once, Run Anywhere.
Application of java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc
2.FEATURES OF JAVA:
. Simple – Java fallows the basic Syntax of C,C++. If you understand the basic concept of
OOPS then it is easy to master in java.
Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on publickey encryption
Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
Multithreaded − With Java's multithreaded feature In java we can write programs that can
perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
Interpreted − Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the linking
is an incremental and light-weight process.
High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to
choose the algorithm. Its implementation has been provided by Sun and other companies.
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of
JVM is created.
Verifies code
Executes code
Method area: In the method area, all class level information like class name, immediate
parent class name, methods and variables information etc. are stored, including static
variables. There is only one method area per JVM, and it is a shared resource.
Heap area: Information of all objects is stored in the heap area. There is also one Heap
Area per JVM. It is also a shared resource.
Stack area: For every thread, JVM creates one run-time stack which is stored here. Every
block of this stack is called activation record/stack frame which stores methods calls. All
local variables of that method are stored in their corresponding frame. After a thread
terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.
PC Registers: Store address of current execution instruction of a thread. Obviously, each
thread has separate PC Registers.
Native method stacks: For every thread, a separate native stack is created. It stores native
method information.
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions.
Java Native Interface (JNI) :
It is an interface that interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to
be called by C/C++ libraries which may be specific to hardware.
Native Method Libraries :
It is a collection of the Native Libraries(C, C++) which are required by the Execution
Engine.
Class It should start with the uppercase letter. public class Employee
It should be a noun such as Color, Button, {
System, Thread, etc. //code snippet
Use appropriate words, instead of }
acronyms.
Java follows camel-case syntax for naming the class, interface, method, and variable.
If the name is combined with two words, the second word will start with uppercase letter
always such as actionPerformed(), firstName, ActionEvent, ActionListener, etc.
5.Datatypes in java:
Byte:
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an integer.
Short:
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
Int:
Long:
Float:
Float is mainly used to save memory in large arrays of floating point numbers
Double
This data type is generally used as the default data type for decimal values, generally the
default choice
Boolean:
Char:
Non-primitive data types or reference data types refer to instances or objects. They cannot
store the value of a variable directly in memory. They store a memory address of the
variable. Unlike primitive data types we define by Java, non-primitive data types are user-
defined.
Array
An array holds elements of the same type. It is an object in Java, and the array name (used for
declaration) is a reference value that carries the base address of the continuous location of
elements of an array
String
The String data type stores a sequence or array of characters. A string is a non-primitive data
type, but it is predefined in Java. String literals are enclosed in double quotes.
Interface
An interface is declared like a class. The key difference is that the interface contains abstract
methods by default; they have nobody.
Enum
An enum, similar to a class, has attributes and methods. However, unlike classes, enum
constants are public, static, and final (unchangeable – cannot be overridden). Developers
cannot use an enum to create objects, and it cannot extend other classes. But, the enum can
implement interfaces.
class sample {
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;
Output;
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Java Keywords:
Java Keywords can not be used as a variable name.
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
6.Control statements:
7.Selection statements:
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
if(condition) {
Example:
int x = 10;
int y = 12;
} }
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
Syntax:
if(condition) {
else{
int x = 10;
int y = 12;
} else {
}}
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true.
Syntax :
if(condition 1) {
else if(condition 2) {
else {
Example:
if(city == "Meerut") {
System.out.println("city is meerut");
System.out.println("city is noida");
System.out.println("city is agra");
}else {
System.out.println(city);
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
Syntax
if(condition 1) {
statement 1;
if(condition 2) {
statement 2;
else{
statement 2;
example.
public class Student {
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
}else if(address.contains("Noida")) {
}else {
System.out.println(address.split(",")[0]);
}else {
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable
which is being switched. The switch statement is easier to use instead of if-else-if statements.
It also enhances the readability of the program.
The syntax.
switch (expression){
case value1:
statement1;
break;
.
case valueN:
statementN;
break;
default:
default statement;
}
Example:
int k=20;
switch(k)
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
case 3:
System.out.println("3");
break;
Iterative statements:
For Loop
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization;condition;incr/decr){
//code to be executed
Example:
for(int i=1;i<=20;i++){
System.out.println(i);
While Loop
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
1. while(condition){
2. //code to be executed
3. }
3. int j=1;
4. while(j<=10){
5. System.out.println(j);
6. j++;
7. }
8. } }
do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.The Java do-while loop is executed at least once because condition is
checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Example:
int j=1;
do{ System.out.println(j);
j++;
}while(j<=10);
}}
Break Statement
The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
Example:
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. break;
6. }
7. System.out.println(i);
8. }
9. }
10. }
Continue Statement
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.
Example:
3. for(int k=1;k<=10;k++){
4. if(k==5){
5. continue;
6. }
7. System.out.println(k);
8. }
9. }
10. }
Return statement:
The purpose of using a Return statement is to terminate the current method of execution and
transfer the control to the next "calling method".
There are two types of Return statements, which are "Return with a value" and "Return
without a value".
Example:
class continue_statement
System.out.println("Using Return");
if (age<18)
8.Arrays in java:
1. Normally, an array is a collection of similar type of elements which has contiguous
memory location.
2. Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements in
a Java
3. Array in Java is index-based, the first element of the array is stored at the 0th index, 2 nd
element is stored on 1st index and so on i.e. Arrays in Java are 0 base indexed.
Syntax :
dataType arrayRefVar[];
Example :
double myList[];
Advantages
● Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Disadvantages
● Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
dataType arr[];
Instantiation of an Array
class Main{
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
System.out.println(a[i]);
}}
Example:2
double total = 0;
total += myList[i];
} System.out.println("Total is "
+
total);
} System.out.println("Max is "
max);
Multidimensional Array
In such case, data is stored in row and column based index (also known as matrix
form).
Syntax:
dataType arrayRefVar[][];
Example:
Example of Matrix:
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example:
class Testarray3{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
System.out.println();
}}
3D Array:
int arr[4][5][8];
class HelloWorld {
public static void main( String args[] ) {
int arr[][][] = {
{ {0,1,2}, {2,3,4}, {6,7,1} },
{ {6,7, 1}, {8,9, 2}, {9,14, 22} }
};
System.out.println(arr[0][0][0]);
}
}
}
}
}
The java command-line argument is an argument i.e. passed at the time of running the
java program.
The arguments passed from the console can be received in the java program and it can
be used as an input.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command
prompt.
The users can pass the arguments during the execution bypassing the command-line
arguments inside the main() method.
Example:
class A{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
output:
Bhanu
25.8
abc
Unit-2
1.Strings:
A Java string is a sequence of characters that exists as an object of the class java.lang. Java
strings are created and manipulated through the string class. Once created, a string is
immutable -- its value cannot be changed.
1.String literal.
1.String literal:
String s="welcome";
2. Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is created and placed in the
pool.
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
3. In the above example, only one object will be created. Firstly, JVM will not find any
string object with the value "Welcome" in string constant pool that is why it will create
a new object. After that it will find the string with the value "Welcome" in the pool, it
will not create a new object but will return the reference to the same instance.
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Example:
char ch[]={'s','t','r','i','n','g','s'};
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
3 String substring (int i): Return the substring from the ith index character to end.
" Programming".substring(3); // returns “gramming”
4 String substring (int i, int j): Returns the substring from i to j-1 index.
String s1 = ”hello”;
String s2 = ”world”;
String output = s1.concat(s2); // returns “helloworld”
6 int indexOf (String s): Returns the index within the string of the first occurrence of the
specified string.
considerations.
the middle.
The String class equals() method compares the original content of the string. It compares
values of string for equality.
class Teststringcomparison1{
String s1="Sachin";
String s2="Sachin";
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
The double equal (==) operator compares two objects references to check whether
they refer to same instance. This also will return true on successful match else returns false.
Example:
class Teststringcomparison3{
String s2="Sachin";
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
} }
The String class compareTo() method compares values lexicographically and returns an integer value that
describes if first string is less than, equal to or greater than second string.
Example:
class Teststringcomparison4{
String s1="hello";
String s2="Hello";
System.out.println(s1.compareTo(s2)); //32(s1>s2)
System.out.println(s2.compareTo(s1)); //-32(s1<s2)
5.Procedural Programming:
Procedural Programming can be defined as a programming model which is derived from structured
programming, based upon the concept of calling procedure. Procedures, also known as routines,
subroutines or functions, simply consist of a series of computational steps to be carried out.
During a program’s execution, any given procedure might be called at any point, including by
other procedures or itself.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL,
BASIC, Pascal and C.
Advantages of Procedural Programming
Overloading Both operators and methods can be Allows only method overloading
overloaded
Compatibility with Other Compatible with C Not compatible with any language
Programming Languages
Pointers Supports pointers Supports pointers with restrictions
Documentation Comment Does not support documentation Has built-in documentation comments
comments support (/**…**/), allowing Java files
to have their own documentation
Thread Support Does not support thread Has built-in thread support via the
“thread” class
Compilation and Interpretation C is only compiled and not interpreted. Java is both compiled and interpreted.
Pointers C has support for pointers. Java does not support pointers.
Threading C is not intrinsically a multithreaded Java supports threading.
language; however, there are many
libraries that add threading functionality.
Garbage Collection In C, Garbage Collection needs to be In Java, Garbage Collector
done manually. automatically does the Garbage
Collection.
Application The C programming language is used Java can be used only for Application
for both system programming as well as programming and not for system
Application programming. programming.
Functional Units In C, mostly the functional units are In Java, mostly the functional units are
functions as it is a procedural objects as it is an object-oriented
programming language. programming language.
5.Java Methods
The method in Java or Methods of Java is a collection of statements that perform some
specific task and return the result to the caller. A Java method can perform some
specific task without returning anything. Java Methods allow us to reuse the code
without retyping the code. In Java, every method must be part of some class that is
different from languages like C, C++, and Python.
1. A method is like a function i.e. used to expose the behavior of an object.
2. It is a set of codes that perform a particular task.
Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
In general, method declarations have 6 components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed
in your application. In Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its
subclass/es
private: It is accessible only within the class in which it is defined.
default: It is declared/defined without using any modifier. It is accessible within the
same class and package within which its class is defined.
Note: It is Optional in syntax.
2. The return type: The data type of the value returned by the method or void if does
not return a value. It is Mandatory in syntax.
3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different. It is Mandatory in syntax.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded
by their data type, within the enclosed parenthesis. If there are no parameters, you must
use empty parentheses (). It is Optional in syntax.
5. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s). It is Optional in syntax.
6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations. It is Optional in syntax.
1. Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point.
2. User-defined Method
Syntax:
// Instance Method
void method_name(){
import java.io.*;
// Different class
class class1 {
void add()
int a= 2;
int b= 3;
System.out.println("The sum of 2 and 3 is :" + (a+b));
class GFG {
// Static method
obj.add();
System.out.println("GFG!");
A static method in Java is a method that is part of a class rather than an instance of
that class.
Every instance of a class has access to the method.
Static methods have access to class variables (static variables) without using the
class’s object (instance).
Only static data may be accessed by a static method. It is unable to access data that
is not static (instance variables).
In both static and non-static methods, static methods can be accessed directly.
Syntax to declare the static method:
The name of the class can be used to invoke or access static methods.
Syntax to call a static method:
className.methodName();
The static method does not have access to the instance variable
The JVM runs the static method first, followed by the creation of class instances.
Because no objects are accessible when the static method is used. A static method does
not have access to instance variables. As a result, a static method can’t access a class’s
instance variable.
import java.io.*;
// static variable
// instance variable
int b = 50;
void simpleDisplay()
System.out.println(a);
System.out.println(b);
}
System.out.println(a);
// main method
obj.simpleDisplay();
staticDisplay();
The methods can be accessed only using The method is only accessed by class
object reference. name.
Static Block
In simpler language whenever we use a static keyword and associate it to a block then
that block is referred to as a static block. This code inside the static block is executed
only once: the first time the class is loaded into memory. So in order to call any static
block, there is no specified way as static block executes automatically when the class is
loaded in memory.
class Test {
static int i;
int j;
// Case 3: Static block
static
i = 10;
// Class 2
// Main class
class GFG {
// following statement.
System.out.println(Test.i);
}
Arrays to methods
import java.util.Scanner;
Recursion in Java:
In Java, Recursion is a process in which a function calls itself directly or indirectly is
called recursion and the corresponding function is called a recursive function.
class GFG
// recursive method
int fact(int n)
int result;
if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
class Recursion {
System.out.println("Factorial of 3 is "
+ f.fact(3));
System.out.println("Factorial of 4 is "
+ f.fact(4));
System.out.println("Factorial of 5 is "
+ f.fact(5));
int a;
int b;
// Parameterized constructor
Test(int a, int b)
this.a = a;
this.b = b;
void display()
object.display();
}
}
Object:
Class:
A class is a blueprint of the object. When you define a class, you define a
blueprint for an object. A class contains data members (variables) and member
functions.
Encapsulation:
Abstraction:
Abstraction means avoiding unnecessary and irrelevant information and only
showing the specific details of what users want to see. Or in other words,
abstraction refers to showing only the most relevant information while hiding the
details.
Example:
Every time you log into your email account (Gmail, Yahoo, Hotmail, or official
mail), many processes occur in the backend. You do not have any control over
how the password is verified, which keeps it safe from misuse.
Polymorphism:
Polymorphism means taking more than one form. Suppose you are in a
classroom at that time. You behave like a student. When you are in the market at
that time, you behave like a customer. When you are at your home at that time,
you behave like a son or daughter. In this case, one person is exhibiting a variety
of behaviors.
we use Operator overloading and Function overloading to achieve
polymorphism.
Operator Overloading: The process of making an operator exhibit different
behaviors in different instances is known as Operator overloading.
Function Overloading: When a single function name is used to execute many
tasks, this is known as function overloading.
Inheritance:
When one class inherits the capabilities from another class or when one object
acquires all the properties and behaviors of its parent object, then it is known
as Inheritance. It helps to reduce the code size.
A real-life example of inheritance is a child and parents. All the properties of the
father are inherited by his son.
What are the benefits and disadvantages of OOP and what are the applicationsof
OOP?
Principles or Advantages
1. Through inheritance, we can eliminate redundant code and extend the use
of existing class.
2. We can build a program from standing working modules that can
communicate with one another rather than having to start writing the code from
scratch. This leads to saving of development time and highs productivity.
3. The principles of data hiding helps programmer to build a secure
program. This codeis not overrun other parts of programs.
4. It is possible to have multiple objects to co exists without an interference.
5. It is easy to partition the work in a project based on objects.
6. The data-centered design approach to capture more details of model in an
implementation form.
7. Object oriented systems can be easily upgraded from small to large systems.
8. Message passing techniques for communication between objects make the
interface descriptions, with external systems much simpler.
9. Software complexity can be easily managed.
Applications of OOP
The most popular application Of OOP has been in the area of user interface design
such as windows. OOP is useful in this type of applications because it can simplify
complex problem. The promising areas for application of OOP include:
Steep learning curve: The thought process involved in oop’s may not be
natural for some people and it can take to get used to it. It is a programming
techniques such as inheritance and polymorphism can be challenging to a
comprehend initially
Lager program size
Slower programs
Not suitable for all types of problems
The private access modifier is specified using the keyword private. The methods or
data members declared as private are accessible only within the class in which they are
declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because
private means “only visible within the enclosing class”.
protected means “only visible within the enclosing class and any
subclasses”
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
8.Constructors:
A constructor is similar to a method that is used to initialize the instance
variables of the objects of a class. The only purpose of a constructor is to
initialize the instance variables. A constructor has the following
characteristics.
1.Constructor name and class name must be same.
2. Constructor does not return any value. They do not specify a return type,
even we should not write void also.
3. A constructor may or may not have parameters. Parameters are variables to receive data
from outside into the
import java.io.*;
class GFG
{
GFG()
{
System.out.println("Default constructor");
}
public static void main(String[] args)
{
GFG ob = new GFG();
}
}
import java.io.*;
class student
{
String name;
int id;
student(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG {
public static void main(String[] args)
{
student ob = new student("avinash", 68);
System.out.println("studentName :" + ob.name
+ " and studentId :" + ob.id);
}
}
9.Inheritance in Java
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and
methods) of another class. In Java, Inheritance means creating new classes based on
existing ones. A class that inherits from another class can reuse the methods and fields
of that class. In addition, you can add new fields and methods to your current class as
well.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.
class Animal
void eat( )
System.out.println("eating...");
void bark( )
{
System.out.println("barking...");
class TestInheritance
d.bark();
d.eat();
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. In the below
image, class A serves as a base class for the derived class B, which in turn serves
as a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.
import java.io.*;
import java.lang.*;
import java.util.*;
class one
System.out.println("Geeks");
System.out.println("for");
System.out.println("Geeks");
}
public class Main {
g.print_geek();
g.print_for();
g.print_geek();
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the
derived classes B, C, and D.
class A
System.out.println("Class A");
}
}
class B extends A
System.out.println("Class B");
class C extends A
System.out.println("Class C"); }
class D extends A
System.out.println("Class D");
}
public class Test {
obj_B.print_A();
obj_B.print_B();
obj_C.print_A();
obj_C.print_C();
obj_D.print_A();
obj_D.print_D();
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.
5. Hybrid Inheritance(Through Interfaces)
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support
multiple inheritances with classes, hybrid inheritance is also not possible with classes.
In Java, we can achieve hybrid inheritance only through Interfaces.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
This scenario occurs when a derived class and base class has the same data members. In
that case, there is a possibility of ambiguity for the JVM.
class Vehicle
void display()
class Test
small.display();
This is used when we want to call the parent class method. So whenever a parent and
child class have the same-named methods then to resolve ambiguity we use the super
keyword.
class Person
void message()
{
System.out.println("This is person class\n");
void message()
void display()
message();
super.message();
class Test
s.display();
Person()
Student()
super();
class Test