0% found this document useful (0 votes)
4 views35 pages

java(class2)

The document explains access specifiers in Java, which control the visibility of class members, including default, public, protected, and private. It also covers object instantiation, static fields and methods, command-line arguments, method creation and calling, method parameters, method overloading, and the use of the 'this' keyword to differentiate between instance and local variables. Overall, it provides a comprehensive overview of Java programming concepts related to classes and methods.

Uploaded by

yastabassum767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views35 pages

java(class2)

The document explains access specifiers in Java, which control the visibility of class members, including default, public, protected, and private. It also covers object instantiation, static fields and methods, command-line arguments, method creation and calling, method parameters, method overloading, and the use of the 'this' keyword to differentiate between instance and local variables. Overall, it provides a comprehensive overview of Java programming concepts related to classes and methods.

Uploaded by

yastabassum767
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Access Specifiers:

Access specifer also called as access modifier that explains to the


JVM(Java Virtural Machine) about the accessing permission of members
of a class. The access specifier of a member (instance variable or
method) specifies the scope of the member where it can be accessed.
The access specifers are four. They are default, public, protected and
private.

Access Specifier : default

If no access specifier is given for the member then java takes default as
default access specifier for that member. The default members can be
accessed inside and outside the class but in the same package.

Outside the package the default members can not be accessed.


Example:
class A
{
int x;
// access specifier is default
void sum) // access specifier is default
Access Specifier : public

The members declared with the access specifier public are said to be
public members and such members can be accessed in the same and
other classes regardless of their package as well as all its subclasses.

Public members can be defined using public keyword.

Example:
class A
{
public int x;
public void sum( )
{..
}

Access Specifier : protected

The members declared with the access specifier protected are said to
be protected members and such members can be accessed in the same
class and in any other classes of same package and its subclasses of
other packages. Protected members can be defined with the keyword
protected.
Example:
class A
protected int x;
protected void sum( )
{
Access Specifier : private

The members declared with the access specifer private are said

to be private members and such private members should be accessed


only with in the same class in which they are created and they cannot
be accessed outside the class. Private members can be declared with
the keyword private.

Example:
class A
{
private int x;
private void sum( )
Objects:
A class specification only declares the structure of objects and it must be
instantiated in order to make use of the services provided by it.
This process of creation of objects (variables) of the class is called class
instantiation. It is the definition of an object that actually creates objects in the
program by setting aside memory space for its storage. Hence, a class is like a
blueprint of an object and it indicates how the instance variables and methods are
used when the class is instantiated. The necessary resources are allocated only
when a class is instantiated.
Creation of classes is nothing but creation of userdefined datatype.
We can use this new datatype (class) to create variables of the class type.
However, creating objects of a class is a two-step process.
First, we must declare a reference variable of the class.
This reference variable does not define an object, instead it creates a variable that
stores reference(address) of an object.
Syntax:
classname obj;
Here obj is a reference variable of classname that can store
reference(address) of object of classname.
Second, we must create an actual physical copy of the object and assign it to the
reference variable. This can be done using the new operator.
Syntax:
obj=new classname;
The new operator allocates memory of classnamel) dynamically (at run-time)
which is said to be an object and whose address is assigned to reference variable
obj.
We can also create objects in single statement using the following
syntax:
classname obj=new classname();
In java objects are instantiated at runtime using new operator.
Accessing Class members:
Once an object of a class has been created, there must be a provision to access its
members. This can be achieved by using the member access operator • (dot).
1) Syntax for accessing instance variable of a class
Objectname.instancevariable;
1) Syntax for accessing methods of a class
Objectname.methodname([Arguments list...]);

Example:
class Sample{
private int x=10;
public int y=20;
protected int z=30;
int p=40;
}
class Sam{
public static void main(String[] args){
sample obj=new sample();
//System.out.print("\n obj.x=" +obj.x)//error
System.out.println("obj.y="+obj.y);
System.out.println("obj.z="+obj.z);
System.out.println("obj.p="+obj.p);
}
}
Output:
obj.y=20
obj.z=30
obj.p=40
Explanation:
In the main() the statement sample obj=new sample(); the new allocates memory
of sample() which is the actual object and whose address 1001 is assigned to obj .
The private variable x is not accessed outside the class therefore it is commented,
otherwise it is an error. Where as public, protected and default variables y, z and
p can be accessed outside the class using objectname as a result we got the
output as shown in above output.

Static Fields and Methods


The static keyword in java is used for memory management mainly. We can apply
java static keyword with variables, methods, blocks and nested class. The static
keyword belongs to the class than instance of the class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
Java static variable
If you declare any variable as static, it is known static variable.

The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,college
name of students etc.

The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).

Example of static variable:


//Program of static variable
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Output:111 Karan ITS
222 Aryan ITS
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 object of a class. o A


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

static method can access static data member and can change the value
of it.
Example of static method:
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n)
{ rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display(); s2.display(); s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

public static methods

The public static methods of a class can be accessed outside the class
using class name without using object name. The public access specifier
specifies that the method can be accessed outside the class. The static
modifier specifies that the method can be accessed using classname.
Example program
Bin>edit static1 java
class A{
public static void show(Strings args[]){
System.out.print("\n show of A...");
}
}
class static1
{
public static void main(String[] args){
A.show();
}
}

Bin> javac static1.java


Bin>java static1
show of A..
Explanation:
The A class contain show() method which is public static method. In the
main(), the show() method is called using A classname because public
static methods can be accessed using classname.

Why main() method is declared as public and static

java command as

When a java program is executed at the command prompt using the


java command as

Bin> java static1

The JVM takes the static class name and using this class name it calls
the main() method as static1.main(). Like this main() method is called
from out side the class using class name therefore main() method
should be declared as public and static.

Command-Line Arguments:

It is also possible to pass values to main() method and it can be passed


from command line because main() method is called from command-
line.

Passing arguments from command line to the main() method is known


as command line arguments.

Values passed from command-line exist in the form of strings therefore

the argument in the main() is defined as an array of String type. public


static void main(String argvs[])

argv is an array of String that can store any number of values passed

from command-line
Example Program:

This program takes values from command-line and prints on the

monitor.

Bin>edit cline java


class cline
public static void main (String argv[]){
int i;
System. out.print("\n No. of arguments="+argv. length);
System. out print (In Argument values...");
for (1-0; 1<argv. length; i++){
System. out print ("\n" +argv [i]);
}
}
}
Bin>javac cline java
Bin>java cline 100 Vaagdevi 20.5

Java Methods:
A method in Java is a block of code within a class that performs a
specific task.
A method is a block of code which only runs when it is called
You can pass data, known as parameters, into a method.
Why use methods? To reuse code: define the code once, and use it
many times.
Create a Method

A method must be declared within a class. It is defined with the name


of the method, followed by parentheses (). Java provides some pre-
defined methods, such as System.out.println(), but you can also create
your own methods to perform certain actions

public class Main {


static void myMethod() {
// code to be executed
}
}
Example Explained

 myMethod() is the name of the method


 static means that the method belongs to the Main class and not
an object of the Main class.
 void means that this method does not have a return value

Call a Method:

 To call a method in Java, write the method's name followed by


two parentheses () and a semicolon;
 In the following example, myMethod() is used to print a text (the
action), when it is called
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "I just got executed!"

A method can also be called multiple times:

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

// I just got executed!


// I just got executed!
// I just got executed!

Java Method Parameters:


Parameters and Arguments:

 Information can be passed to methods as a parameter.


Parameters act as variables inside the method.
 Parameters are specified after the method name, inside the
parentheses. You can add as many parameters as you want, just
separate them with a comma.
 The following example has a method that takes
a String called fname as parameter. When the method is called,
we pass along a first name, which is used inside the method to
print the full name:
Example
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

When a parameter is passed to the method, it is called an argument.


So, from the example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.

Multiple Parameters:

You can have as many parameters as you like:


Example
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}

public static void main(String[] args) {


myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}

// Liam is 5
// Jenny is 8
// Anja is 31

Method Overloading:
Method overloading in Java is a feature that allows a class to have multiple methods with the
same name but different parameter lists. This is a form of compile-time polymorphism, where
the correct method to be executed is determined during compilation based on the method
signature.
Key characteristics of method overloading:
 Same Method Name: All overloaded methods within a class share the same name.
 Different Parameter Lists: The parameter lists must differ in at least one of the following ways:
o Number of parameters: The methods have a different count of parameters.
o Data type of parameters: The methods have parameters of different data types.

Example:
class Calculator {
// Overloaded method to add two integers
public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two doubles


public double add(double a, double b) {
return a + b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Calls add(int, int)
System.out.println(calc.add(5, 10, 15)); // Calls add(int, int, int)
System.out.println(calc.add(5.5, 10.2)); // Calls add(double, double)
}
}

The this keyword:


Local variables of methods can have the same name as that of instance
variable. This is possible because local variable is local to the function in
which they are created where as instance variables are global to the
same class i.e they can be accessed by any method of same class
When local variables (or) parameters of methods is having the same
name as that of instance variables of class then the java gives first
preference to the local variables of same function as a result only local
variables are accessed in the method and not the instance variables
(global variables).
Example:

Bin>edit accounts.java
class bank
private String name; private int accno;
public void setbank (String name, int accno)
name = name;
accno=accno;
}
public void show( )
System. out, print ("Inname="+name+"\nacno="+accno) ;
class accounts{
public static void main (String agrv[])
bank obj-new bank ( );
obj setbank ("kumar", 105);
System. out print ("\nBank Account...");
obj. show( );
}
}
Bin> javac accounts.java
Bin> java accounts
Bank Account...
name=null
accno=0
Explanation:

In the main, obj is the object instantiated to bank class as shown in


memory. The statement obj.setbank("kumar",105) calls the
setbank(String name, int accno) method inside the class. The values
"Kumar", 105 passes to name and acco of setbank (). In this case the
local variables name, aceno and instance variables of class are having
same names. Therefore in the method only local variables are accessed
but not the instance variables of class or object. As a result, the local
variable values are again assigned to same local variables but not to the
instance variables of object. The statement obj.showbank() displays
name-null and accno=0 of obj.
To overcome the above problem or drawback we can use this keyword.
The this keyword is a predefined reference variable in java which can
store address of any object. When a method is called by an object, the
address of object is assigned to this reference variable, and this
reference variable can be used in the method to know the address of
object or to access the members of object or class explicitly. When
instance variables of class and local variables of methods have same
name then instance variables can be accessed using this reference
variable explicitly.
When the method is terminated the this reference variable created
is automatically deleted.
Solution for the above program using this reference variable.
Example:
Bin>edit accounts java
class bank
{

private String name;


private int accno;
public void setbank ( String name, int acono){
this name - name;
this. accno-accno;
}
public void showbank ( )
System. out print ("\n name =" +name+"\n accno ="+accno);
}
class accounts
{
public static void main (String agrv[])
{
bank obj-new bank ( );
obj. setbank ("kumar", 105) ;
System.out.print ("\n Bank Account...");
obj. showbank ( );
}
}
Bin>javac accounts.java
Bin>java accounts
Bank Account... name=kumar
accno=105
Explanation:
In the main), obj is the object instantiated to bank class as shown in
memory. The statement obj setbank("kumar", 105) calls the
setbank(String name, int accno) method inside the class. The values
"kumar", 105 passes to name and aceno of setbank (). When the
setbank) is called by obj whose address(101) is stored into this
reference variable as shown in above memory.
Now this reference variable is pointing to obj. Inside the setbank() the
name and acco of obj is accessed using this reference variable.
Therefore the local variables name(kumar) and accno(105) values are
assigned to instance variables of object as shown in memory. When the
setbank() is terminated the this reference variable is automatically
deleted from memory. The statement obj.showbank() displays name
and aceno of obj as shown in output.
Points to Remember:
1.The this keyword is predefined reference variable in Java.
2.The this reference variable should be used only inside the methods of
class.
3.When we want to know the address of called object inside the
method then we can use this reference variable.
4.The this reference variable should be used to access the members of
the object explicitly.
5.The this reference variable should not be used in the static methods
because static methods can be called without using object but using
class name.

Recursion:
Recursion in Java is a programming technique where a method calls itself to solve a
problem. This approach is typically used when a problem can be broken down into smaller,
similar subproblems.
public class Factorial {
public static int calculateFactorial(int n) {
// Base case: factorial of 0 or 1 is 1
if (n == 0 || n == 1) {
return 1;
} else {
// Recursive step: n * factorial of (n-1)
return n * calculateFactorial(n - 1);
}
}

public static void main(String[] args) {


int number = 5;
int result = calculateFactorial(number);
System.out.println("Factorial of " + number + " is: " + result); // Output: Factorial of 5 is: 120
}
}

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

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

String[] cars;
We have now declared a variable that holds an array of strings. To
insert values to it, you can place the values in a comma-separated list,
inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Change an Array Element
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo

Garbage Collection: Garbage collection is the automatic process of


eliminating unnecessary objects from memory.
we always free up the space from the memory to avoid program from
terminating abnormally i.e. causing out of memory errors.

Programming languages like c/c++, deleting unused objects is done


manually. But in java, unused objects deleted automatically.

In java, memories of objects are allocated dynamically at runtime using


new operator. This dynamically allocated objects memories can not be
deleted manually by the programmer using the delete operator as in C+
+. In java the memories of objects are automatically deleted by garbage
collector.

The garbage collector is a special program which is a part of jvm that is


automatically executed by jvm and comes into the heap memory where
it deletes all unwanted memories of objects. The unwanted or waste
objects are identified if the object does not have any reference
variables on stack.

This process of de-allocation of memory by the garbage collector is


called as garbage collection. The garbage collector is not simply
executed if one or more waste objects exist in heap. The garbage
collector is executed periodically at any time and its execution is under
the control of jvm. The different java run-time(jvm) implementations
have different approaches to garbage collection. Therefore we need
not to think about the memory deallocation while writing the program
as it is handled by the jvm.

Advantage of garbage collector

1. No wastage of memory:

The memories of waste objects are automatically deleted by garbage

collector.

Java Comments :
The java comments are statements that are not executed by the
compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or any
statement. It can also be used to hide program code for specific time.

There are 2 types of comments in java.

1. Single Line Comment

2. Multi Line Comment

Java Single Line Comment


The single line comment is used to comment only one line.

Syntax:
1. //This is single line comment
Example:
public class CommentExample1 {
public static void main(String[] args) {
int i=10;//Here, i is a variable
System.out.println(i);
}
}
Output: 10

Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:
/* This is multi line comment */
Example:
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:10

Variables and in Java


Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

There are two types of data types in java: primitive and non-primitive.

Types of Variable
There are three types of variables in java:

o local variable
o instance variable
o static variable
1) Local Variable

A variable which is declared inside the method is called local variable.

2) Instance Variable

A variable which is declared inside the class but outside the method, is
called instance variable . It is not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be


local.

Scope and Life Time of Variables:

The scope of a variable defines the section of the code in which the
variable is visible. As a general rule, variables that are defined within a
block are not accessible outside that block. The lifetime of a variable
refers to how long the variable exists before it is destroyed. Destroying
variables refers to deallocating the memory that was allotted to the
variables when declaring it. We have written a few classes till now. You
might have observed that not all variables are the same. The ones
declared in the body of a method were different from those that were
declared in the class itself. There are three types of variables: instance
variables, formal parameters and local variables.

Instance variables :
Instance variables are those that are defined within a class itself and
not in any method or constructor of the class. They are known as
instance variables because every instance of the class (object) contains
a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have
already seen about it earlier. The lifetime of these variables is the same
as the lifetime of the object to which it belongs. Object once created do
not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about
Java's automatic garbage collector later on.

Argument variables :

These are the variables that are defined in the header oaf constructor
or a method. The scope of these variables is the method or constructor
in which they are defined. The lifetime is limited to the time for which
the method keeps executing. Once the method finishes execution,
these variables are destroyed.

Local variables :

A local variable is the one that is declared within a method or a


constructor (not in the header). The scope and lifetime are limited to
the method itself.

Java Strings: Strings are used for storing text.


A String variable contains a collection of characters surrounded by double quotes

Example
Create a variable of type String and assign it a value:
String greeting = "Hello";
Data Types:
Type Conversion or Type Casting

Conversion from one data type value to another data type value is
known as type conversion or type casting. Java supports type
conversion in two ways.

1. Implicit Conversion

2. Explicit Conversion

Implicit Conversion
Converting from one datatype value to another datatype value
internally by the java language is known as implicit conversion. Java
automatically converts one type value to another provided the
following two conditions are satisfied.

1. Destination and source variables types should be type compatible.

(i.e. the data types of variables should belong to same data type
category.)

2. The destination variable data type size is larger than source variable
data type.

Example:

2.
int x; short y=20; x=y;
/ / Correct: because & occupies 4 bytes and y occupies 1/2 bytes and both are type compatible.
int x=30; short y;
y=X;
/ / Error: because size of y is 2 bytes and a size is 4 / / bytes. Therefore
destination variable(y) size is

// not larger than source(x).

int a=3000;

float f;

f= a; // Error: because the data types of variables are not / / compatible


i.e f belongs to float data type / / category and a belongs to integer
data type

// category.

Explicit type conversion


When the above two conditions are not satisfying, then the java does
not allow implicit conversion. Therefore we have to convert the source
data type value to the destination data type explicitly and this
conversion is known as explicit conversion. This can be done by using
the type casting method.
Example:
int x=300; byte y;
y= (byte) x;
→ Explicit type casting.
In the above example, value of x is converted into 1 byte and stores

into y. This conversion method is known as explicit type casting


method.

When java does not convert automatically, then we should convert

explicitly as shown above.

Operators in java
Operator in java is a symbol that is used to perform operations. For
example: +, -, *, / etc.

There are many types of operators in java which are given below:
 Unary Operator,
 Arithmetic Operator,
 shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.
Expressions:
Expressions are essential building blocks of any Java program, usually created to
produce a new value, although sometimes an expression simply assigns a value to
a variable. Expressions are built using values, variables, operators and method
calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are
three types of
expressions in Java:
 Those that produce a value, i.e. the result of (1 + 1)
 Those that assign a variable, for example (v = 10)
 Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators
that modify the state (i.e. memory) of a program.

Control Statements:

Inheritance in Java:
Java Inheritance is a fundamental concept in 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.
Example:
class A{

public void sum(int a,int b){


System.out.println(" the sum of two numbers are:"+(a+b));
}
}

class B extends A{

public void sub(int a, int b){


System.out.println(" the sub of two numbers are:"+(a-b));
}
}
class C extends B{
public void mul(int a,int b){
System.out.println(" the mul of two numbers:"+(a*b));
}
}
class D {
public static void main(String[] args){
C obj=new C();
obj.sum(10,20);
obj.sub(50,40);
obj.mul(300,5);
}
}
output:
the sum of two numbers are:30
the sub of two numbers are:10
the mul of two numbers are:1500

polymorphism:

Polymorphism in Java is a core concept of Object-Oriented Programming (OOP) that enables


objects to take on multiple forms or behaviors. The term "polymorphism" originates from
Greek words "poly" (many) and "morphs" (forms), signifying "many forms."

Key Aspects of Polymorphism in Java:


 Definition:
Polymorphism allows a single action to be performed in different ways, depending on the
object type involved. It enables a common interface to be used for multiple underlying data
types or classes.
 Achieving Polymorphism:
 Method Overloading: Defining multiple methods with the same name but different signatures
within a single class.
 Method Overriding: A subclass re-implementing a method inherited from its superclass,
providing its own specific behavior.

Method Overriding:
Method overriding in Java is a feature of object-oriented programming that allows a subclass to
provide a specific implementation for a method that is already defined in its superclass. This is a
core concept of polymorphism, specifically runtime polymorphism, where the method to be
executed is determined at runtime based on the actual object type.
Key characteristics and rules of method overriding:
 Inheritance:
Method overriding can only occur between a superclass and its subclass, establishing an "IS-A"
relationship.
 Same Signature:
The overriding method in the subclass must have the exact same name, return type (or a
covariant return type, which is a subtype of the superclass method's return type), and
parameters as the method in the superclass.
 Access Modifiers:
The access modifier of the overriding method in the subclass must be the same or more
permissive than the overridden method in the superclass (e.g., if the superclass method
is protected, the subclass method can be protected or public, but not private).
 No Overriding of private or final methods:
private methods are not inherited and thus cannot be overridden. final methods cannot be
overridden because their implementation is fixed.
 static methods:
static methods cannot be overridden; if a subclass defines a static method with the same
signature as a static method in the superclass, it is considered method hiding, not overriding.

Example:
class A{

public void sum(){


System.out.println("the sum is methos of class A");
}
public void sub(){
System.out.println("the sub is method of class B");
}
public void mul(){
System.out.println("the div is method of class A");

}
}
class B extends A{

public void div(){


System.out.println("the mul is method of class B");
}
public void sub(){ //Here We Are overriding sub() method of parent class.
System.out.println("the sub is a method of class A but overriding in class B");
}
}
class C{
public static void main(String[] args){

B obj=new B();
obj.sum();
obj.sub();
obj.mul();
obj.div();
}
}
output:
the sum is method of class A
the sub is a method of class A but overriding in class B
the mul is method of class A
the div is method of class B

Encapsulation:
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of a private variable

 You learned from the previous chapter that private variables can only be accessed
within the same class (an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.
 The get method returns the variable value, and the set method sets the value.
 Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:

public class Person {


private String name; // private = restricted access

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

public class Main {


public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John"; // error
System.out.println(myObj.name); // error
}
}

If the variable was declared as public, we would expect the following output:
However, as we try to access a private variable, we get an error:
Instead, we use the getName() and setName() methods to access and update the variable:
public class Main {
public static void main(String[] args) {
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}

// Outputs "John"

Why Encapsulation?
 Better control of class attributes and methods
 Class attributes can be made read-only (if you only use the get method), or write-
only (if you only use the set method)
 Flexible: the programmer can change one part of the code without affecting other parts
 Increased security of data

Exceptions:
Different types of errors can occur while running a program - such as coding mistakes, invalid
input, or unexpected situations.

When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).

Exception Handling (try and catch)


Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.

It uses different keywords:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.

The try and catch keywords come in pairs:

try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.


public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10


at Main.main(Main.java:4)

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

The output will be:


Something went wrong.

Finally
The finally statement lets you execute code, after try...catch, regardless of the result:

Example

public class Main {


public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}

The output will be:


Something went wrong.
The 'try catch' is finished.

You might also like