0% found this document useful (0 votes)
13 views

Java 2

The document discusses object oriented concepts in Java including classes, objects, inheritance, polymorphism, and methods. It defines what a class and object are, and describes class variables, methods, and constructors. Inheritance and polymorphism are also covered.

Uploaded by

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

Java 2

The document discusses object oriented concepts in Java including classes, objects, inheritance, polymorphism, and methods. It defines what a class and object are, and describes class variables, methods, and constructors. Inheritance and polymorphism are also covered.

Uploaded by

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

Course Objectives:

Object oriented concepts in Java and apply for solving the problems.

Course Outcomes:

Summarize the fundamental features like Interfaces, Exceptions and Collections.

UNIT II:

CLASSES, INHERITANCE, POLYMORPHISM: Classes and Objects: Classes, Objects,


creating objects, methods, constructors- constructor overloading, cleaning up unused objects-
Garbage collector, class variable and methods- static keyword, this keyword, arrays, Command
line arguments, Nested Classes

Strings: String, StringBuffer, String Tokenizer Inheritance and Polymorphism: Types of


Inheritance, deriving classes using extends keyword, super keyword, Polymorphism – Method
Overloading, Method Overriding, final keyword, abstract classes.
Bharath Yannam
class

➢ A class is a user defined blueprint or prototype from which objects are created.

➢ It represents the set of properties or methods that are common to all objects of one type.

➢ It is a logical entity. It can't be physical.

A class in Java can contain:

✓ Fields

✓ Methods

✓ Constructors

✓ Blocks

✓ Nested class and interface


Bharath Yannam
Syntax to declare a class
class <class_name> type method2(parameters)
{
{
// declare instance variable
// body of method
type var1;
}
type var2;
//… //..

Type varN; type methodN(parameters)

{
//declare methods
// body of method
type method1(parameters)
}
{
// body of method } }
object
➢ An entity that has state and behaviour is known as an object.

➢ Object is an instance of a class.

An object has three characteristics:

❖State: It is represented by attributes of an object. It also reflects the properties of an object.

❖Behaviour: It is represented by methods of an object. It also reflects the response of an object with
other objects.

❖Identity: It gives a unique name to an object and enables one object to interact with other objects.

➢ When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behaviour of the class.

➢ But the values of those attributes are unique for each object. A single class may have any number
of instances.
Bharath Yannam
Syntax for Creating Objects:

class_name object_name = new class_name();

Example

public class Main{

String s = "Hello World";

public static void main(String args[]) {

Main a = new Main(); //creating an object

System.out.println(a.s); //Outputs Hello World

Bharath Yannam
Reference Variables and Assignment
➢ A variable that holds reference of an object is called a reference variable.

➢ Variable is a name that is used to hold a value of any type during program execution.

➢ If the type is an object, then the variable is called reference variable, and if the variable holds
primitive types(int, float, etc.), then it is called non-reference variables.

➢ Reference variable basically points to an object stored into heap memory.

➢ Default value of a reference variable always a null.

Bharath Yannam
➢ In Java, if we have two different objects of the same class, and if we assign the reference of
one object to the other reference of the other object, then they refer to the same object.

Test t1 = new test ();

Test t2 = t1;

➢ Here an object t1 is created for Test class and assigned to another object t2.

➢ t1 and t2 will both refer to the same object.

➢ The assignment of t1 to t2 did not allocate any memory or copy and part of the original
object.

➢ It simply makes t2 refer to the same object, as does t1.

➢ Thus, any changes made to the object through t2 will affect the object to which t1 is referring

Bharath Yannam
Java Methods
➢ A method is a block of code that performs a specific task.

➢ It provides the reusability of code. We write a method once and use it many times

➢ We can also provides the easy modification and readability of code using methods.

➢ The method is executed only when we call or invoke it.

➢ The most important method in Java is the main() method.

In Java, there are two types of methods:

❖User-defined Methods: We can create our own method based on our requirements.

❖Standard Library Methods: These are built-in methods in Java that are available to use.
Bharath Yannam
Method Declaration
➢ The method declaration provides information about method attributes.

➢ It has six components that are known as method Declaration

The syntax to declare a method is:

modifier static returnType nameOfMethod (parameter1, parameter2, ...) {

// method body }

Bharath Yannam
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

➢ Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:

❖Public: The method is accessible by all classes when we use public specifier in our
application.

❖Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.

❖Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.

❖Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Bharath Yannam
➢ Return Type: Return type is a data type that the method returns. If the method does not
return anything, we use void keyword.

➢ Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by
its name.

➢ Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.

➢ Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Bharath Yannam
Example:

public static int min(int n1, int n2) {

int min;

if (n1 > n2)

min = n2;

else

min = n1;

return min;

Bharath Yannam
Method Calling

➢ For using a method, it should be called.

➢ There are two ways in which a method is called i.e., method returns a value or returning
nothing (no return value).

➢ The process of method calling is simple. When a program invokes a method, the program
control gets transferred to the called method.

➢ This called method then returns control to the caller in two conditions, when −

❖the return statement is executed.

❖it reaches the method ending closing brace.

Bharath Yannam
public class MyClass {

static void myMethod() {

System.out.println("My name is: myMethod!");

public static void main(String[] args) {

myMethod();

In the above example if you remove the static keyword, java complains that you can’t
call a method from a static function:
Bharath Yannam
If you don’t want to use static, you can only call instance method:

public class MyClass {

void myMethod() {

System.out.println("My name is: myMethod!");

public static void main(String[] args) {

MyClass x= new MyClass();

x.myMethod();

Bharath Yannam
A method can also be called multiple times:

public class MyClass {

static void myMethod() {

System.out.println("My name is: myMethod!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

} }

Bharath Yannam
Returning a Value from a Method
➢ You declare a method's return type in its method declaration. Within the body of the method,
you use the return statement to return the value.

➢ Any method declared void doesn't return a value. It does not need to contain a return
statement.

➢ If you try to return a value from a method that is declared void, you will get a compiler error.

➢ Any method that is not declared void must contain a return statement with a corresponding
return value, like this:

return returnValue;

➢ The data type of the return value must match the method's declared return type; you can't
return an integer value from a method declared to return a boolean.
Bharath Yannam
public class MyClass { public class MyClass {

void myMethod() { int myMethod() {


int a=10; int a=10;
return a; return a;
} }

public static void main(String[] args) { public static void main(String[] args) {
MyClass x= new MyClass(); MyClass x= new MyClass();

int c=x.myMethod(); int c=x.myMethod();


System.out.println(c); System.out.println(c);

} }
} }
Method Parameters
➢ Information can be passed to methods as public class Math {
parameter. static int multiplyBytwo(int number)
➢ Parameters act as variables inside the method. {

➢ Parameters are specified after the method return number * 2;


name, inside the parentheses. }
➢ You can add as many parameters as you public static void main(String[] args)
want, just separate them with a comma. {

int result = multiplyBytwo(2);

System.out.println("The output is:


" + result);

} } Bharath Yannam
Multiple Parameters

You can have as many parameters as you like.

public class Math {

static int sum(int num1, int num2) {

return num1 + num2;

public static void main(String[] args) {

int result = sum(2,3);

System.out.println("Sum of numbers is: " + result);

Bharath Yannam
Method Overloading
➢ If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.

➢ If we have to perform only one operation, having same name of the methods increases the
readability of the program

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java


❖By changing number of arguments
❖By changing the data type

➢ In Java, Method Overloading is not possible by changing the return type of the method only.
Bharath Yannam
Method Overloading: changing no. of arguments

class Adder{

static int add(int a,int b) {

return a+b;

static int add(int a,int b,int c) {

return a+b+c;

} }

class Test{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

Bharath Yannam
Method Overloading: changing data type of arguments:

class Adder{

static int add(int a, int b) {

return a+b;

static double add(double a, double b) {

return a+b;

} }

class TestOverloading2{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

Bharath Yannam
passing objects to methods
➢ In Java there is always pass by value and not by pass by reference.

➢ when a primitive type is passed to a method as argument then the value assigned to this primitive is
get passed to the method and that value becomes local to that method.

➢ which means that any change to that value by the method would not change the value of primitive
that you have passed to the method.

➢ While creating a variable of a class type, we only create a reference to an object.

➢ Thus, when we pass this reference to a method, the parameter that receives it will refer to the same
object as that referred to by the argument.

➢ This effectively means that objects act as if they are passed to methods by use of call-by-reference.

➢ Changes to the object inside the method do reflect in the object used as an argument.

Bharath Yannam
class Ob System.out.println(c);

{ else

int a,c; System.out.println(b.a);

Ob(int i) }

{ public static void main(String[] args)

a=i; {

c=a+5; Ob b1= new Ob(20);

} Ob b2= new Ob(10);

void print(Ob b) { b1.print(b1);

if(b.a==a) } }

Bharath Yannam
Returning Objects from Methods

➢ Like any other data datatype, a method can returns object.

➢ When a method returns an object, the return type of the method is the name of the class to

which the object belongs

➢ The normal return statement in the method is used to return the object

➢ In order to return an object from a Java method, you must first declare a variable to hold a

reference to the object.

Bharath Yannam
class Sample { } }

int value; public class Ro

Sample(int i) { {

value=i; public static void main(String[] args)

} {

public Sample twice() Sample s1=new Sample(10);

{ Sample s2;

Sample x= new Sample(value*2); s2=s1.twice();

return x; } s2.show(); } }

public void show() {


System.out.println(value);
Bharath Yannam
Variable-Length Arguments

➢ Java has a feature that simplifies the creation of methods that need to take a variable number
of arguments.

➢ This feature is called varargs and it is short-form for variable-length arguments.

➢ A method that takes a variable number of arguments is a varargs method.

➢ The varrags allows the method to accept zero or muliple arguments.

➢ Before varargs either we use overloaded method or take an array as the method parameter.

➢ If we don't know how many argument we will have to pass in the method, varargs is the better
approach.

Bharath Yannam
Syntax : for (int i: a)

The varargs uses ellipsis i.e. three dots System.out.print(i + " ");
after the data type. Syntax is as follows: System.out.println();
return_type method_name(data_type... variableNa }
me){}

Example: public static void main(String args[])

class Test1 {

{ fun(100); // one parameter

fun(1, 2, 3, 4); // four parameters


static void fun(int ...a)
fun(); // no parameter
{
} }
System.out.println("Number of
arguments: " + a.length);
Bharath Yannam
Constructors
➢ A constructor is a block of codes similar to the method.

➢ It is called when an instance of the class is created.

➢ At the time of calling constructor, memory for the object is allocated in the memory.

➢ There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

key differences between a constructor and a method:

➢ A constructor doesn’t have a return type.

➢ The name of the constructor must be the same as the name of the class.

➢ Unlike methods, constructors are not considered members of a class.

➢ A constructor is called automatically when a new instance of an object is created.

Bharath Yannam
Example:

class Test {

Test() {

// constructor body

Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return

type.

Bharath Yannam
Default Constructor Example

A constructor is called "Default Constructor" class Bike1{

when it doesn't have any parameter. Bike1()

Syntax of default constructor: {

<class_name>(){} System.out.println("Bike is created");

public static void main(String args[]){

Bike1 b=new Bike1();

} }
Bharath Yannam
Parameterized Constructor
➢ A constructor which has a specific number of class Pc
parameters is called a parameterized {
constructor. Pc(int a, int b)
➢ The parameterized constructor is used to {
provide different values to distinct objects.
System.out.println(a+b);
}
public static void main(String[] args)
{
Pc p1=new Pc(5,6);
}
}

Bharath Yannam
Constructor Overloading

➢ constructor is just like a method but without return type.

➢ It can also be overloaded like Java methods.

➢ Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists.

➢ They are arranged in a way that each constructor performs a different task.

➢ They are differentiated by the compiler by the number of parameters in the list and their
types.

Bharath Yannam
class Pc public static void main(String[] args)

{ {

Pc(int a, int b) Pc p1=new Pc(5,6);

{ Pc p2=new Pc('5');

System.out.println(a+b); }

} }

Pc(char a)

System.out.println(a);

Bharath Yannam
new Keyword
➢ The Java new keyword is used to instantiates a class by allocating memory for a new object
and returning a reference to that memory.

➢ We can also use the new keyword to create the array object.

steps when creating an object from a class −

➢ Declaration − A variable declaration with a variable name with an object type.

➢ Instantiation − The 'new' keyword is used to create the object.

➢ Initialization − The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.

Syntax

NewExample obj=new NewExample();

Bharath Yannam
Example 1 public static void main(String[] args) {

Create an object using new keyword and invoking NewExample1 obj=new NewExample1();

the method using the corresponding object obj.display();


reference. }

public class NewExample1 { }

void display()

System.out.println("Invoking Method");

Bharath Yannam
Example 2

Create an array object using the new keyword.

public class NewExample4 {

static int arr[]=new int[3];

public static void main(String[] args) {

System.out.println("Array length: "+arr.length);

}
Bharath Yannam
static keyword
➢ The static keyword in Java is used for memory management mainly.

➢ The static keyword belongs to the class than an instance of the class.

The static can be:

❑ Variable (also known as a class variable)

❑ Method (also known as a class method)

❑ Block

❑ Nested class

Bharath Yannam
Java static variable

➢ If you declare any variable as static, it is known as a static variable.

➢ The static variable can be used to refer to the common property of all objects

➢ The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

➢ It makes your program memory efficient (i.e., it saves memory).

Bharath Yannam
class H18 public static void main(String[] args)
{ {
static int a=20,b=30; H18 h= new H18();
H18()
{ H18 h1= new H18();
a++; H18 h2= new H18();
b++; dis();
} dis();
static void dis() }
{
System.out.println(a+" "+b); }
}

Bharath Yannam
Java static method

➢ If you apply static keyword with any method, it is known as static method.

➢ A static method belongs to the class rather than the object of a class.

➢ A static method can be invoked without the need for creating an instance of a class.

➢ A static method can access static data member and can change the value of it.

Restrictions for the static method

➢ The static method can not use non static data member or call non-static method directly.

➢ this and super cannot be used in static context.

Bharath Yannam
class Calculate{

static int cube(int x){

return x*x*x;

public static void main(String args[]){

int result=Calculate. Cube(5);

System.out.println(result);

Bharath Yannam
this Keyword
➢ this keyword in Java is a reference variable that refers to the current object of a method or a
constructor.

➢ The main purpose of using this keyword in Java is to remove the confusion between class
attributes and parameters that have same names.

Usage of Java this keyword:

➢ this can be used to refer current class instance variable.

➢ this can be used to invoke current class method (implicitly)

➢ this() can be used to invoke current class constructor.

➢ this can be passed as an argument in the method call.

Bharath Yannam
this: to refer current class instance variable: this.fee=fee;
➢ The this keyword can be used to refer current
class instance variable. }

➢ If there is ambiguity between the instance void display(){System.out.println(rollno+" "


variables and parameters, this keyword +name+" "+fee);
resolves the problem of ambiguity.
} }
class Student{
class TestThis2{
int rollno;
public static void main(String args[]){
String name;
Student s1=new Student(111,"ankit",5000f);
float fee; Student s2=new Student(112,"sumit",6000f);
Student(int rollno,String name,float fee){ s1.display();

this.rollno=rollno; s2.display();

}}
this.name=name;
Bharath Yannam
this: to invoke current class method: void n(){

➢ You may invoke the method of the current System.out.println(“hello n");

class by using the this keyword. this.m();

➢ If you don't use the this keyword, compiler }

automatically adds this keyword while }


invoking the method. Let's see the example class TestThis4{

Example: public static void main(String args[]){

class A{ A a=new A();

a.n();
void m()
}}
{

System.out.println("hello m");
}
Bharath Yannam
this() : to invoke current class constructor: A(int x){

➢ The this() constructor call can be used to this();

invoke the current class constructor. System.out.println(x);

➢ It is used to reuse the constructor. }

class TestThis5{
class A{
public static void main(String args[]){
A()
A a=new A(10);
{
}}
System.out.println("hello a");

Bharath Yannam
this: to pass as an argument in the method: void p(){

➢ The this keyword can also be passed as an m(this);

argument in the method. }

➢ It is mainly used in the event handling. Let's public static void main(String args[]){

see the example: Cs s1 = new Cs();

s1.p();

class Cs{ }

}
void m(Cs obj){

System.out.println("method is invoked");

Bharath Yannam
this: to pass as argument in the constructor class Yx
call {
We can pass the this keyword in the constructor int a=2;
also. It is useful if we have to use one object in Yx()
multiple classes. {
Xy x=new Xy(this);
class Xy }
{ void display()
Yx y; {
System.out.println(a);
Xy(Yx y)
}
{ public static void main(String[] args)
this.y=y; {
y.display(); Yx y= new Yx();
} }
}
}

Bharath Yannam
Wrapper Classes
➢ A Wrapper class is a class whose object wraps or contains primitive data types.

➢ When we create an object to a wrapper class, it contains a field and in this field, we can store
primitive data types.

➢ It provides the mechanism to convert primitive into object and object into primitive.

Need of Wrapper Classes

➢ They convert primitive data types into objects. Objects are needed if we wish to modify the
arguments passed into a method (because primitive types are passed by value).

➢ The classes in java.util package handles only objects and hence wrapper classes help in this case
also.

➢ Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.

➢ An object is needed to support synchronization in multithreading.

Bharath Yannam
Primitive Data types and their Corresponding Wrapper class:

Bharath Yannam
Autoboxing
➢ The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing.
➢ for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float,
boolean to Boolean, double to Double, and short to Short.

public class WrapperExample1{


public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}

Bharath Yannam
Unboxing
➢ The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing.

➢ It is the reverse process of autoboxing.

public class WrapperExample2{


public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}

Bharath Yannam
Garbage Collection
➢ In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming the
runtime unused memory automatically.

➢ It is a way to destroy the unused objects.

➢ To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically.

➢ So, java provides better memory management.

Advantages:

➢ It makes java memory efficient because garbage collector removes the unreferenced objects
from heap memory.

➢ It is automatically done by the garbage collector(a part of JVM) so we don't need to make
extra efforts.
Bharath Yannam
How an object be unreferenced?

➢ By nulling the reference

Employee e=new Employee();

e=null;

➢ By assigning a reference to another

Employee e1=new Employee();

Employee e2=new Employee();

e1=e2;//now the object referred by e1 is available for garbage collection

➢ By anonymous object

new Employee();

Bharath Yannam
finalize()
➢ The finalize() method of Object class is a method that the Garbage Collector always calls just
before destroying the object which is eligible for Garbage Collection, to perform clean-up
activity.

➢ Clean-up activity means closing the resources associated with that object like Database
Connection, Network Connection or we can say resource de-allocation.

➢ Once the finalize method completes immediately Garbage Collector destroy that object.

Syntax:

protected void finalize() throws Throwable

Bharath Yannam
➢ Object class contains the finalize method hence finalize method is available for every java
class. Bcz, Object is the superclass of all java classes.

➢ it is available for every java class hence Garbage Collector can call the finalize method on any
java object

➢ finalize() method releases system resources before the garbage collector runs for a specific
object.

➢ JVM allows finalize() to be invoked only once per object.

gc() method

➢ The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

public static void gc(){}

Bharath Yannam
Example of garbage collection: H25 h1=new H25();

class H25 H25 h2=new H25();

{ h1=null;

protected void finalize() h2=null;

{ System.gc();

System.out.println("objectis garbage collected"); } }

public static void main(String[] args)

System.out.println("garbage");
Bharath Yannam
Command Line Arguments

➢ 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.

➢ Passing command-line arguments in a Java program is quite easy.

➢ They are stored as strings in the String array passed to the args parameter of main() method
in Java.

➢ You can pass N (1,2,3 and so on) numbers of arguments

Bharath Yannam
public class CommandLine {

public static void main(String args[]) {

for(int i = 0; i<args.length; i++) {

System.out.println("args[" + i + "]: " + args[i]);

Bharath Yannam
BufferedReader Class
➢ Java provides several mechanisms to read from File.

➢ The most useful package that is provided for this is the java.io

➢ BufferedReader class is used to read the text from a character-based input stream.

➢ The constructor of this class accepts an InputStream object as a parameter.

➢ This class provides a method named read() and readLine() which reads and returns the
character and next line from the source.

➢ Instantiate an InputStreamReader class bypassing your InputStream object as a parameter.

➢ Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a


parameter.

➢ Now, read data from the current reader as String using the readLine() or read() method.
Bharath Yannam
import java.io.*;

public class BufferedReaderExample{

public static void main(String args[])throws Exception{

InputStreamReader r=new InputStreamReader(System.in);

BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");

String name=br.readLine();

System.out.println("Welcome "+name);

Bharath Yannam
Scanner Class

➢ Scanner is a class in java.util package used for obtaining the input of the primitive types like int,
double, etc. and strings.

➢ Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It
provides many methods to read and parse various primitive values.

➢ To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream.

➢ We may pass an object of class File if we want to read input from a file.

➢ To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can use nextShort()

➢ To read strings, we use nextLine().

Bharath Yannam
Input Types

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

Bharath Yannam
import java.util.*;

public class ScannerExample {

public static void main(String args[]){

Scanner in = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = in.nextLine();

System.out.println("Name is: " + name);

in.close();

Bharath Yannam
Controlling Access to Class Members
Access level modifiers determine whether other classes can use a particular field or invoke a
particular method.

There are four types of Java access modifiers:

➢ Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.

➢ Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.

➢ Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.

➢ Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
Bharath Yannam
outside
Access outside
within class within package package by
Modifier package
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

Bharath Yannam
class Test6 }

{ class Test7

private void display() {

{ public static void main(String[] args)

System.out.println("hello"); {

} Test6 a=new Test6();

void dis() a.display();

{ a.dis();

System.out.println("hello java class"); }

} }

Bharath Yannam
Arrays
➢ An array is a collection of similar types of data.

➢ Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

➢ The elements of an array are stored in a contiguous memory location.

➢ We can store only a fixed set of elements in a Java array.

➢ Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

➢ array itself has a type that specifies what kind of elements it can contain.

➢ An int array can contain int values, for example, and a String array can contain strings.

Bharath Yannam
some important points about Java arrays:

➢ In Java all arrays are dynamically allocated.

➢ Since arrays are objects in Java, we can find their length using the object property length.

➢ A Java array variable can also be declared like other variables with [] after the data type.

➢ The variables in the array are ordered and each have an index beginning from 0.

➢ Java array can be also be used as a static field, a local variable or a method parameter.

➢ The size of an array must be specified by an int or short value and not long.

➢ The direct superclass of an array type is Object.

➢ Every array type implements the interfaces Cloneable and java.io.Serializable.

Bharath Yannam
Declaring Array Variables:

➢ To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference.

➢ To declare an array, define the variable type with square brackets:

Syntax:

❖dataType[] arr; // preferred way. (or)

❖dataType []arr; (or)

❖dataType arr[];

Example:

String[] cars;

Bharath Yannam
Creating (Instantiation) Arrays:

You can create an array by using the new operator

Syntax:

datatype[] arrayRefVar;

arrayRefVar=new datatype[size];

The above statement does two things −

➢ It creates an array using new dataType[arraySize].

➢ It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −

dataType[] arrayRefVar = new dataType[arraySize];


Bharath Yannam
Initialize Arrays:

In Java, we can initialize arrays during declaration.

//declare and initialize and array

int[] age = {12, 4, 5, 2, 5};

(OR)

// declare and Instantiate an array

int[] age = new int[5];

// initialize array
age[0] = 12;

age[1] = 4;

age[2] = 5;

..
Bharath Yannam
Access Elements of an Array:

We can access the element of an array using the index number.

// access array elements

array[index]

Bharath Yannam
Example: Access Array Elements

class Main {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5};

// access each array elements

System.out.println("Accessing Elements of Array:");

System.out.println("First Element: " + age[0]);

System.out.println("Second Element: " + age[1]);

System.out.println(“Third Element: " + age[2]);

} }
Bharath Yannam
Example to print array:

class Testarray1{

public static void main(String args[]){

int a[]={33,3,4,5};//declaration, instantiation and initialization

//printing array

for(int i=0;i<a.length;i++)//length is the property of array

System.out.println(a[i]);

for(int i:a)

System.out.println(i);

}}

Bharath Yannam
Types of Array in java:

There are two types of array.

➢ Single Dimensional Array

➢ Multidimensional Array

Single dimensional array − A single dimensional array of Java is a normal array where, the array
contains sequential elements (of same type) −

int[] myArray = {10, 20, 30, 40}

Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two


dimensional array is an array of one dimensional arrays and a three dimensional array is an array of
two dimensional arrays.

dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar;

Example:

int[][] arr=new int[3][3];//3 row and 3 column


Bharath Yannam
Example of Multidimensional Array:

class Testarray3{

public static void main(String args[]){

//declaring and initializing 2D array

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();

} }}
Bharath Yannam
import java.util.*; }
class Test22 for(int i=0;i<3;i++)
{ {
public static void main(String[] args) for(int j=0;j<3;j++)
{ {
Scanner s=new Scanner(System.in); for(int k=0;k<4;k++)
int[][][] a=new int[3][3][4]; {
for(int i=0;i<3;i++) System.out.print(a[i][j][k]+" ");
{ }
for(int j=0;j<3;j++) System.out.println();
{ }
for(int k=0;k<4;k++) System.out.println();
{ }
a[i][j][k]=s.nextInt(); }
} } }
Bharath Yannam
Irregular(Jagged) Arrays
➢ When you allocate memory for a multidimensional array, you need to specify only the
memory for the first (leftmost) dimension.
➢ You can allocate the remaining dimensions separately.
➢ For example, the following code allocates memory for the first dimension of table when it is
declared. It allocates the second dimension manually.

➢ When declaring an irregular array, at least one dimension does not contain a specific value
(empty brackets [ ]).

Bharath Yannam
Example:

➢ int[][] A = new int[3][5]; // regular array

➢ int[][] B = new int[3][]; // irregular two-dimensional array

➢ int[][][] C = new int[3][4][]; // irregular three-dimensional array

➢ int[][][] D = new int[3][][]; // irregular three-dimensional array

➢ // int[][][] E = new int[][][]; // error

Bharath Yannam
Difference between irregular arrays and regular arrays:

➢ In a regular array, the number of elements in each dimension is known in advance. This
number is set at the time of allocating memory for the array with the new operator.

➢ In an irregular array, the number of elements in at least one dimension is unknown. This
number may vary within this dimension.

For example. Let a regular array A be declared for which memory is allocated

• int[][] A = new int[3][5]; // regular array, number of items = 3 * 5 = 15

• If irregular array is declared

• int[][] B = new int[3][]; // irregular array, the total number of elements is unknown

• it is known that this array B contains 3 one-dimensional arrays. The number of elements in
any of these arrays is unknown.
Bharath Yannam
class Test25 a[i][j]=i+j;

{ } }

public static void main(String[] args) for(int i=0;i<2;i++)

{ {

int[][] a= new int[2][]; for(int j=0;j<5;j++)

a[0]=new int[5]; {

a[1]=new int[5]; System.out.print(a[i][j]+" ");

for(int i=0;i<2;i++) }

{ System.out.println();

for(int j=0;j<5;j++) }

{ } }
Bharath Yannam
import java.util.*; for(int i=0;i<a.length;i++)
class Jarray {
{ for(int j=0;j<a[i].length;j++)
public static void main(String[] args) {
{ a[i][j]=s.nextInt();
int b,c,d; }
Scanner s=new Scanner(System.in); }
b=s.nextInt(); for(int i=0;i<a.length;i++)
c=s.nextInt(); {
d=s.nextInt(); for(int j=0;j<a[i].length;j++)
int a[][] = new int[3][]; {
System.out.println(a[i][j]);
a[0] = new int[b]; }
}
a[1] = new int[c];
}
a[2] = new int[d]; }

Bharath Yannam
Array Copy in Java
Given an array, we need to copy its elements in a different array

Methods:
➢ Iterating each element of the given original array and copy one element at a time
Iterating each element of the given original array and copy one element at a time. With
the usage of this method, it guarantees that any modifications to b, will not alter the original
array a.
➢ Using clone() method :
Object cloning means to create an exact copy of the original object.
➢ Using arraycopy() method:
We can also use System.arraycopy() Method. The system is present in java.lang
package. Its signature is as :
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Bharath Yannam
import java.util.*; for(int i=0;i<a.length;i++) for(int i:d)
import java.lang.*; { {
class Clone a[i]=s.nextInt(); System.out.println(i);
} }
{
int[] e=new int[a.length]; }
static void dis(int a[]) for(int i=0;i<a.length;i++) }
{ {
for(int i:a) e[i]=a[i];
System.out.println(i); }
for(int i:e)
}
{
public static void main(String[] System.out.println(i);
args)
}
{
Scanner int[] c=a.clone();
s=new Scanner(System.in); dis(c);
int b=4; int d[]= new int[a.length];
System.arraycopy(a, 0, d,
int[] a=new int[b]; 0, 3);
Bharath Yannam
Anonymous Array
An array in Java without any name is known as an anonymous array. It is an array just
for creating and using instantly. Using an anonymous array, we can pass an array with user
values without the referenced variable.

Properties of Anonymous Arrays:

➢ We can create an array without a name. Such types of nameless arrays are called anonymous
arrays.

➢ The main purpose of an anonymous array is just for instant use (just for one-time usage).

➢ An anonymous array is passed as an argument of a method.

Syntax:

new <data type>[]{<list of values with comma separator>};


Bharath Yannam
Example:
class Ann
{
static void dis(int[] a)
{
for(int i:a)
System.out.println(i);
}
public static void main(String[] args)
{
dis(new int[]{1,2,3,4,5});
}
}

Bharath Yannam
String
➢ In Java, string is basically an object that represents sequence of char values.

➢ Java String class provides a lot of methods to perform operations on strings.

➢ The Java String is immutable which means it cannot be changed.

➢ Whenever we change any string, a new instance is created.

➢ An array of characters is same as Java string.

example:

char[] ch={‘h’,’e’,’l’,’l’,’o’};

String s=new String(ch);

is same as:

String s=“Hello";

Bharath Yannam
create a string object
There are two ways to create String object:

➢ By string literal

➢ By new keyword

String Literal:

➢ Java String literal is created by using double quotes.

String s="welcome";

➢ 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


Bharath Yannam
new keyword:

String s=new String("Welcome");

➢ JVM will create a new string object in normal memory, and the literal "Welcome" will be
placed in the string constant pool.

➢ The variable s will refer to the object in a memory

Bharath Yannam
StringExample.java:

public class Example{

public static void main(String args[]){

String s1="java";//creating string by Java string literal

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch);//converting char array to string

String s3=new String("example");//creating Java string by new keyword

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

}}
Bharath Yannam
String Constructor
➢ String class supports several types of constructors in Java APIs.

The most commonly used constructors of the String class are as follows:

➢ String()

String s = new String();

➢ String(String str)

String s2 = new String("Hello Java");

➢ String(char chars[ ])

char chars[ ] = { 'a', 'b', 'c', 'd’ }; String s3 = new String(chars);


➢ String(char chars[ ], int startIndex, int count)

char chars[ ] = { 'w', 'i', 'n', 'd', 'o', 'w', 's' }; String str = new String(chars, 2, 3);
Bharath Yannam
➢ String(byte byteArr[ ])

byte b[] = { 97, 98, 99, 100 }; // Range of bytes: -128 to 127. These byte values will be
converted into corresponding characters.

String s = new String(b);

➢ String(byte byteArr[ ], int startIndex, int count)

byte b[] = { 65, 66, 67, 68, 69, 70 }; // Range of bytes: -128 to 127.

String s = new String(b, 2, 4); // CDEF

Bharath Yannam
String length()
➢ The Java String class length() method finds the length of a string

➢ The signature of the string length() method is : public int length()

public class LengthExample{

public static void main(String args[]){

String s1="java";

String s2="program";

System.out.println("string length is: "+s1.length());

System.out.println("string length is: "+s2.length());

}}

Bharath Yannam
concatenation
➢ In Java, String concatenation forms a new String that is the combination of multiple strings.

There are two ways to concatenate strings in Java:

➢ By + (String concatenation) operator

String s=“Java"+" Program";

➢ By concat() method

String s1="Java ";

String s2=“Program";

String s3=s1.concat(s2);

Bharath Yannam
to String()
➢ A toString() is an in-built method in Java that returns the value given to it in string format.

➢ Any object that this method is applied on, will then be returned as a string object.

The toString() method in Java has two implementations:

➢ The first implementation is when it is called as a method of an object instance.

Integer number=10;

System.out.println( number.toString() );

➢ The second implementation is when you call the member method of the relevant class by
passing the value as an argument.

System.out.println(Double.toString(11.0));

Bharath Yannam
Character extraction
➢ The Java String class charAt() method returns a char value at the given index number.

➢ The index number starts from 0 and goes to n-1, where n is the length of the string.

String s1="javaprogram";

System.out.println(s1.charAt(4));

Bharath Yannam
string comparison

➢ We can compare String in Java on the basis of content and reference.

➢ There are three ways to compare String in Java:

1. By Using equals() Method

2. By Using == Operator

3. By compareTo() Method

Bharath Yannam
equals() Method:

The String class equals() method compares the original content of the string. It compares values
of string for equality.

String s1="Java";

String s2="Java";

String s3=new String("Java");

String s4=“Programming";

System.out.println(s1.equals(s2));//true

System.out.println(s1.equals(s3));//true

System.out.println(s1.equals(s4));//false

Bharath Yannam
Using == operator:

String s1="Java";

String s2="Java";

String s3=new String("Java");

System.out.println(s1==s2);//true (because both refer to same instance)

System.out.println(s1==s3);//false(because s3 refers to instance created)

Bharath Yannam
compareTo():

➢ 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.

➢ Suppose s1 and s2 are two String objects. If:

❑s1 == s2 : The method returns 0.

❑s1 > s2 : The method returns a positive value.

❑s1 < s2 : The method returns a negative value.

Bharath Yannam
String s1="Java";

String s2="Java";

String s3=“Program";

System.out.println(s1.compareTo(s2));//0

System.out.println(s1.compareTo(s3));//1(because s1>s3)

System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )

Bharath Yannam
searching strings
➢ The Java String class indexOf() method returns the position of the occurrence of the specified
character or string in a specified string.

➢ There are four indexOf() method in Java


Method Description
int indexOf(int ch) It returns the index position for
the given char value

int indexOf(int ch, int It returns the index position for


fromIndex) the given char value and from
index

int indexOf(String substring) It returns the index position for


the given substring

int indexOf(String substring, int It returns the index position for


fromIndex) the given substring and from
index
Bharath Yannam
Example:

String s1="hello java class and java class is good";

System.out.println(s1.indexOf('j’));// Gives first occurrence of “ j “ in a given sentence

System.out.println(s1.lastIndexOf('j’));// Gives last occurrence of “ j “ in a given sentence

System.out.println(s1.indexOf('j',8));// Gives first occurrence of “ j “ in a given sentence


form location 8

System.out.println(s1.lastIndexOf('j',8));//Gives last occurrence of “ j “ in a given sentence


form location 8

System.out.println(s1.indexOf("class")); // Gives first occurrence of “ class “ in a given


sentence

System.out.println(s1.lastIndexOf("class",15));// Gives last occurrence of “ class“ in a given


sentence

Bharath Yannam
modifying
Java String class replace() method returns a string replacing all the old char to new char.

Example:

String s1="hello java class and java class is good";

System.out.println(s1.replace('j','k'));

System.out.println(s1.replace("java","MD"));

Bharath Yannam
Data conversion
➢ If you want to convert a String to specific data type, We use Wrapper class of the concern
datatype and parseDatype().

➢ We can convert String to an int in java using Integer.parseInt() method.

Example:

String s="200";

int i=Integer.parseInt(s);

Long i1=Long.parseLong(i1)

Bharath Yannam
changing the case

To swap the case of a string, use.

toLowerCase() for uppercase string

toUpperCase() for lowercase string

Example:

String s=“hello”;

System.out.println(“s,toUpperCase());

String s1=“HELLO”;

System.out.println(“s,toLowerCase());

Bharath Yannam
joining

➢ Java String class join() method returns a string joined with a given delimiter.

➢ In the String join() method, the delimiter is copied for each element.

Example:

String s2=String.join("/","12","11");

System.out.println(s2);

Bharath Yannam
split()
➢ The string split() method breaks a given string around matches of the given regular
expression.

➢ After splitting against the given regular expression, this method returns a char array.

Example:

String s1="hello java class and java class is good";

String[] s4=s1.split(" ",3);

for(String k:s4)

System.out.println(k);

Bharath Yannam
StringBuffer Class
➢ Java StringBuffer class is used to create mutable (modifiable) String objects.
➢ The StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.
Constructors:
Constructor Description
StringBuffer() It creates an empty String buffer
with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the
specified string..
StringBuffer(int capacity) It creates an empty String buffer
with the specified capacity as
Example: length.

➢ SrtringBuffer sb=new StringBuffer();


➢ StringBuffer sb=new StringBuffer("Hello Java");
➢ StringBuffer sb = new StringBuffer(20);

Bharath Yannam
Methods

length():

➢ This method is used to find the length of string similar to String class

➢ StringBuffer s=new StringBuffer("hello");

➢ System.out.println(s.length());

Bharath Yannam
capacity():

➢ The capacity() method of the StringBuffer class returns the current capacity of the buffer.

➢ The default capacity of the buffer is 16.

➢ If the number of character increases from its current capacity, it increases the capacity by

(oldcapacity*2)+2.

➢ StringBuffer s=new StringBuffer("java is my favourite language");

➢ System.out.println(s.length());

➢ System.out.println(s.capacity());

Bharath Yannam
ensureCapacity():

➢ The ensureCapacity(int minimumCapacity) method of Java StringBuffer class ensures that the
capacity should at least equal to the specified minimum capcity.

➢ If the current capacity of string buffer is less than the specified capacity, then a new internal array
is allocated with the minimumCapacity or the capacity will increase as (old-capacity * 2) + 2.

Syntax:

public void ensureCapacity(int minimumCapacity)

Example:

System.out.println("Before ensureCapacity “ + "method capacity = “ + str.capacity()); //16

str.ensureCapacity(18);

System.out.println("After ensureCapacity“ + " method capacity = “ + str.capacity()); //34


Bharath Yannam
set Length():

➢ The setLength(int newLength) method of StringBuffer class is the inbuilt method used to set the
length of the character sequence equal to newLength.

➢ If the newLength passed as argument is less than the old length, the old length is changed to the
newLength.

➢ If the newLength passed as argument is greater than or equal to the old length, null characters
are appended at the end of old sequence so that length becomes the newLength argument.

Syntax:

public void setLength(int newLength)

Bharath Yannam
charAt():

➢ The Java String class charAt() method returns a char value at the given index number.

➢ The setCharAt(int index, char ch) method of Java StringBuffer class is used to set the
specified character at the given index.

➢ The specified character altered this sequence by replacing the old character at the given index.

StringBuffer sb = new StringBuffer("abc"); sb.setCharAt(1, 'x');

➢ The Java String class getChars() method copies the content of this string into a specified char
array.

➢ There are four arguments passed in the getChars() method. The signature of the getChars()
method is given below:

Signature:

public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)
Bharath Yannam
append():

The java.lang.StringBuffer.append() method is used public StringBuffer append(char[] str, int offset,

to append the string representation of some int len)

argument to the sequence. public StringBuffer append(CharSequence cs)

There are various overloaded append() methods public StringBuffer append(CharSequence cs,

available in StringBuffer class int start, int end)

Syntax: public StringBuffer append(double d)

public StringBuffer append(float f)


Let's see the different syntax of StringBuffer
append() method: public StringBuffer append(int i)

public StringBuffer append(long lng)


public StringBuffer append(boolean b)
public StringBuffer append(Object obj)
public StringBuffer append(char c)
public StringBuffer append(String str)
public StringBuffer append(char[] str)
public StringBuffer append(StringBuffer sb)
Bharath Yannam
insert():
The insert() method of the Java StringBuffer class is used to insert the given string at the
specified index.
Syntax:
public StringBuffer insert(int offset, boolean b)
public StringBuffer insert(int offset, char c)
public StringBuffer insert(int offset, char[] str)
public StringBuffer insert(int index, char[] str, int offset, int len)
public StringBuffer insert(int dstOffset, CharSequence cs)
public StringBuffer insert(int dstOffset, CharSequence cs, int start, int end)
public StringBuffer insert(int offset, double d)
public StringBuffer insert(int offset, float f)
public StringBuffer insert(int offset, int i)
public StringBuffer insert(int offset, long l)
public StringBuffer insert(int offset, Object obj)
public StringBuffer insert(int offset, String str)
Bharath Yannam
class Sb System.out.println(s1.reverse());

{ System.out.println(s1.capacity());

s1.setLength(50);
public static void main(String[] args)
System.out.println(s1.length());
{
s1=s1.append(“CSE AIML GRIET");
StringBuffer s1=new StringBuffer("hello java");
System.out.println(s1.capacity());
System.out.println(s1);
s1.ensureCapacity(220);
System.out.println(s1.append(" class"));
System.out.println(s1.capacity());
System.out.println(s1.replace(2,4,“java")); }

System.out.println(s1.insert(2,“java")); }

System.out.println(s1.delete(2,4));

Bharath Yannam
String Tokenizer
➢ The java.util.StringTokenizer class allows you to break a String into tokens.

➢ It is simple way to break a String.

Bharath Yannam
Constructors:

Constructor Description

It creates StringTokenizer with specified


StringTokenizer(String str)
string.

It creates StringTokenizer with specified


StringTokenizer(String str, String delim)
string and delimiter.

It creates StringTokenizer with specified


string, delimiter and returnValue. If return
StringTokenizer(String str, String delim, value is true, delimiter characters are
boolean returnValue) considered to be tokens. If it is false,
delimiter characters serve to separate
tokens.

Bharath Yannam
Methods:
Methods Description
It checks if there is more
boolean hasMoreTokens()
tokens available.
It returns the next token
String nextToken() from the StringTokenizer
object.
String nextToken(String It returns the next token
delim) based on the delimiter.
It is the same as
boolean hasMoreElements()
hasMoreTokens() method.
It is the same as nextToken()
Object nextElement()
but its return type is Object.
It returns the total number
int countTokens()
of tokens.

Bharath Yannam
import java.util.*; {
class Sto System.out.println(s1.nextToken());
{ }
public static void main(String[] args)
while(s2.hasMoreTokens())
{
{
StringTokenizer s1=new StringTokenizer("hello System.out.println(s2.nextToken("-"));
java class");
}
StringTokenizer s2=new }
StringTokenizer("hello-java-class");
System.out.println(s1.countTokens()); }
while(s1.hasMoreTokens())
{
System.out.println(s1.nextToken());
}
while(s1.hasMoreElements())

Bharath Yannam
Inheritance
➢ Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object.

➢ The concept of inheritance in Java is that new classes can be constructed on top of older ones.

➢ A class that inherits from another class can reuse the methods and fields of that class. Moreover,
you can add new methods and fields in your current class also.

➢ Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why Do We Need Java Inheritance?

➢ Code Reusability: The code written in the Superclass is common to all subclasses. Child classes
can directly use the parent class code.

➢ Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the
ways by which Java achieves Run Time Polymorphism.

➢ Abstraction: The concept of abstract where we do not have to provide all details is achieved
through inheritance. Abstraction only shows the functionality to the user.
Bharath Yannam
Terms used in Inheritance:

➢ Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

➢ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.

➢ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.

➢ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.

Bharath Yannam
Inheritance Syntax :

class superclass
{
// superclass data variables
// superclass member functions
}
class subclass extends superclass
{
// subclass data variables
// subclass member functions
}

Bharath Yannam
Types of inheritance:

Bharath Yannam
Method Overriding
➢ If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.

➢ When a method in a subclass has the same name, the same parameters or signature, and the
same return type(or sub-type) as a method in its super-class, then the method in the subclass is
said to override the method in the super-class.

Bharath Yannam
Usage

➢ Method overriding is used to provide the specific implementation of a method which is


already provided by its superclass.

➢ Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

➢ The method must have the same name as in the parent class

➢ The method must have the same parameter as in the parent class.

➢ There must be an IS-A relationship (inheritance).

Bharath Yannam
class Vehicle{

void run(){System.out.println("Vehicle is running");}

class Bike2 extends Vehicle{

//defining the same method as in the parent class

void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){

Bike2 obj = new Bike2();//creating object

obj.run();//calling method

Output: Bike is running safely

Bharath Yannam
super Keyword

➢ The super keyword in Java is a reference variable which is used to refer immediate parent
class object.

➢ Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

Usage of Java super Keyword

➢ super can be used to refer immediate parent class instance variable.

➢ super can be used to invoke immediate parent class method.

➢ super() can be used to invoke immediate parent class constructor.

Bharath Yannam
1. super is used to refer immediate parent System.out.println(color);//prints color of
class instance variable. Dog class

We can use super keyword to access the data System.out.println(super.color);//prints col

member or field of parent class. It is used if or of Animal class

parent class and child class have same fields. }

class Animal{ }

String color="white"; class TestSuper1{

public static void main(String args[]){


}
Dog d=new Dog();
class Dog extends Animal{
d.printColor();
String color="black";
}}
void printColor(){
Bharath Yannam
2. super can be used to invoke parent class void
method bark(){System.out.println("barking...");}

The super keyword can also be used to invoke void work(){

parent class method. It should be used if super.eat();

subclass contains the same method as parent bark();


class. }

class Animal{ }

void eat(){System.out.println("eating...");} class TestSuper2{

} public static void main(String args[]){

Dog d=new Dog();


class Dog extends Animal{
d.work();
void eat(){System.out.println("eating
}}
bread...");}
Bharath Yannam
3. super is used to invoke parent class super();
constructor. System.out.println("dog is created");

The super keyword can also be used to invoke }


the parent class constructor. Let's see a simple }
example:
class TestSuper3{
class Animal{ public static void main(String args[]){

Animal(){System.out.println("animal is created Dog d=new Dog();


");} }}

class Dog extends Animal{

Dog(){

Bharath Yannam
final keyword
➢ In Java, the final keyword is used to denote constants. It can be used with variables, methods,
and classes.

➢ Once any entity (variable, method or class) is declared final, it can be assigned only once. That
is,

❑ the final variable cannot be reinitialized with another value

❑ the final method cannot be overridden

❑ the final class cannot be extended

Bharath Yannam
1. Java final Variable

In Java, we cannot change the value of a final variable. For example,

class Main {

public static void main(String[] args) {

// create a final variable

final int AGE = 32;

// try to change the final variable

AGE = 45;

System.out.println("Age: " + AGE);

Bharath Yannam
2. Java final Method:
In Java, the final method cannot be overridden by the child class. For example,

Bharath Yannam
3. Java final Class
In Java, the final class cannot be inherited by another class. For example,

Bharath Yannam
Abstract class
➢ A class which is declared as abstract is known as an abstract class.

➢ It can have abstract and non-abstract methods.

➢ It needs to be extended and its method implemented. It cannot be instantiated.

❑ An abstract class must be declared with an abstract keyword.

❑ It can have abstract and non-abstract methods.

❑ It cannot be instantiated.

❑ It can have constructors and static methods also.

❑ It can have final methods which will force the subclass not to change the body of the
method.

Bharath Yannam
abstract class Swaran {
{ Harsha h=new Harsha();
abstract void show(); h.dis();
void dis() h.show();
{ }
System.out.println("hello"); }
}
}
class Harsha extends Swaran
{
void show()
{
System.out.println("hello show");
}
public static void main(String[] args)

Bharath Yannam
Nested Classes
➢ Java inner class or nested class is a class that is declared inside the class or interface.

➢ We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.

➢ Additionally, it can access all the members of the outer class, including private data members and
methods.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Bharath Yannam
There are four types of nested classes in Java:

Static Nested Class:

➢ Also known as a static inner class, it is a static class that is defined within another class.

➢ It does not have access to the instance-specific data of the outer class but can access its static
members.

➢ You can create an instance of a static nested class without an instance of the outer class.

Bharath Yannam
class Outer { Outer. Nested n = new Outer. Nested ();

static class Nested { n.display();

public void display() }}

System.out.println("NestedClass: This is a static


nested class");

} } }

public class Main

public static void main(String[] args)

{
Bharath Yannam
Inner Class (Non-static Nested Class):

➢ An inner class is a non-static class defined within another class.

➢ It can access both static and instance-specific data of the outer class.

➢ To create an instance of an inner class, you typically need an instance of the outer class.

Bharath Yannam
Bharath Yannam
Local Inner Class:

➢ A local inner class is defined within a method or a code block.

➢ It is only accessible within the method or block in which it is defined.

➢ Local inner classes can access both static and instance-specific data of the enclosing method
or block.

Bharath Yannam
class OuterClass LocalInnerClass localInner = new

{ LocalInnerClass();

localInner.display();
void methodWithLocalInnerClass()
}
{
}
class LocalInnerClass
public class Main
{
{
public void display() public static void main(String[] args)
{ {

System.out.println("LocalInnerClass: This is a OuterClass outer = new OuterClass();


local inner class"); outer.methodWithLocalInnerClass();

} } }}
Bharath Yannam
Anonymous Inner Class:

➢ An anonymous inner class is an inner class without a name that is defined and instantiated at
the same time.

➢ They are often used for creating one-time-use classes and overriding methods or interfaces.

Bharath Yannam

You might also like