SlideShare a Scribd company logo
Java Programming
Manish Kumar
(manish87it@gmail.com)
Lecture- 4
Contents
 Java Methods
 Command Line Arguments
 Constructors
 this Keyword
 super Keyword
 static Keyword
 final Keyword
 finally
Java Methods
 A java method is a set of statements that are used to perform some task.
 Naming Convention –
 Method name should start with lowercase letter.
 If the method name contains multiple words, start it with a lowercase letter followed by an uppercase
letter such as getData().
 Creating Method –
 First you write return type of method then method name.
void show() {
// Statements;
}
 Method Calling – There are two ways in which method is called in java:
 With return a value
 With no return value
Java Methods
With Return a Value
class Test {
public static void main(String args []) {
int c = show();
System.out.println(c);
}
int show() {
int z = 10 + 20;
return z;
}
}
Output - 30
With No Return a Value
class Test {
public static void main(String args []) {
Test t = new Test();
t.show();
}
void show() {
int z = 10 + 20;
System.out.println(z);
}
}
Output - 30
Java Methods
Passing parameters by value:
 Passing Parameters by Value means calling a method with a parameter.
 The order of passing value in calling and called method should be same.
Passing Parameters by Value
class Test {
public static void main(String args []) {
int x = 10, y = 20;
Test t = new Test();
t.show(x, y);
}
void show(int x, int y) {
int z = x + y;
System.out.println(z);
}
}
Output - 30
Java Methods
Method Overloading:
 If a class has more than one method with same name but different parameters is known as Method
Overloading.
 Passing Parameters by Value means calling a method with a parameter.
 There are ways to overload the method in java
 By changing the number of arguments
 By changing the data type
Java Methods
By changing number of arguments
class Test {
void show(int x, int y) {
int z = x + y;
System.out.println("z = "+z);
}
void show(int x, int y, int a) {
int c = x + y + a;
System.out.println("c = "+c);
}
public static void main(String args []) {
int x = 10, y = 20, a = 30;
Test t = new Test();
t.show(x, y);
t.show(x, y, a);
}
}
Output – z = 30
c = 60
By changing the data type
class Test {
void show(int x, int y) {
int z = x + y;
System.out.println("z = "+z);
}
void show(int x, int y, double a) {
double c = x + y + a;
System.out.println("c = "+c);
}
public static void main(String args []) {
int x = 10, y = 20; double a = 30.5;
Test t = new Test();
t.show(x, y);
t.show(x, y, a);
}
}
Output – z = 30
c = 60.5
Command Line arguments
 At runtime, when you will want to pass any information into a program then this is accomplished by passing
command-Line arguments to main().
 They are stored as strings in the String array passed to main( ).
Command-Line Arguments
public class Test {
public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int sum = x+y;
System.out.println("sum: " + sum);
}
}
Execution Steps –
javac Test.java
java Test 10 20
Output – sum = 30
Constructors
 I java, Constructor is a special type of method. It is called at the time of object creation. Memory of the
object is allocated at the time calling constructor.
 Every class must have a constructor. If there is no constructor in class then java compiler automatically
creates a default constructor.
Compiler
 It is used to initialize the object
 Constructor has no return type except current class instance.
 A constructor cannot be declared as final, static or synchronized.
 A class can have more than one constructor i.e., constructor can be overloaded.
 Constructor has the same name as class name.
class Test {
}
class Test {
Test() { }
}
Constructors
 The default constructor is used to provide the default values to the object like zero (0), null, etc., depending
on the data type.
class Test{
int id;
String name;
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Test s1=new Test();
Test s2=new Test();
s1.display();
s2.display();
}
}
Output – 0 null
0 null
Constructors
 In java, there are three types of constructor:
 Parameterized Constructor
 Non – Parametrized Constructor
 Default Constructor
Parameterized and Non-Parameterized Constructor
A constructor has a specific parameter is called Parameterized Constructor. A constructor with no parameter is
called Non-Parameterized Constructor.
Constructors
Parameterized Constructor
class Test{
int id;
String name;
Test(int i, String n){
id = i;
name = n;
}
void show(){
System.out.println("Id = "+id+"t"+"Name = "+name);
}
public static void main(String args[]){
Test t1=new Test(101, "Manish");
t1.show();
}
}
Output – Id = 101 Name = Manish
Non-Parameterized Constructor
class Test{
int id;
String name;
Test(){
id = 101;
name = “Manish”;
}
void show(){
System.out.println("Id = "+id);
System.out.println("Name = "+name);
}
public static void main(String args[]){
Test t1=new Test();
t1.show();
}
}
Output – Id = 101
Name = Manish
Constructors
 In java, there are three types of constructor:
 Parameterized Constructor
 Non – Parametrized Constructor
 Default Constructor
Parameterized and Non-Parameterized Constructor
A constructor has a specific parameter is called Parameterized Constructor. A constructor with no parameter is
called Non-Parameterized Constructor.
Default Constructor
Constructor generated by compiler if there is no constructor in program, that constructor is known as Default
Constructor.
Constructors
Constructor Overloading
Constructor Overloading means that a class having more than one constructor with different parameter.
Constructor Overloading
class Demo{
int id, salary;
String name;
Demo(int i, String n){
id = i;
name = n;
}
Demo(int i, String n, int sal){
id = i;
name = n; salary = sal;
}
void show(){
System.out.println("Id = "+id+"t"+"Name = "+name);
}
void show1(){
System.out.println("Id = "+id+"t"+"Name = "+name+"tSalary = "+salary);
}
public static void main(String args[]){
Demo t=new Demo(101, "Manish");
Demo t1=new Demo(102, "Manish", 2000);
t.show(); t1.show1();
} }
Output – Id = 101 Name = Manish
Id = 102 Name = Manish Salary = 2000
Constructors
Constructor Vs. Method
Java Constructor Java Method
A constructor is used to initialize the
state of an object.
A method is used to expose the behavior
of an object.
A constructor must not have a return
type.
A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default
constructor if you don't have any
constructor in a class.
The method is not provided by the
compiler in any case.
The constructor name must be same
as the class name.
The method name may or may not be same
as the class name.
this Keywords
 In java, this is a reference variable that refers to the current class object.
 this keyword is used to differentiate local and instance variable when both the variable name is same.
 this() must be first statement in constructor.
 To reuse the constructor from constructor is known as Constructor Chaining.
Uses of this keyword
 this keyword is used to call current class method.
 this () is used to invoke current class constructor.
 this can be passed as an argument in method and constructor call.
this (Reference Variable) object
this Keywords
this keyword
class Demo {
int id;
String name;
Demo(int id, String name) {
this.id = id;
this.name = name;
}
void show() {
System.out.println("ID = "+id+"t Name = "+name);
}
public static void main(String args[]) {
Demo d = new Demo(101, "Manish");
d.show();
}
}
Output – Id = 101 Name = Manish
Used to call current class method
class Demo {
void show() {
System.out.println("Hello Show Method");
this.display(); // this.display() is same as display()
}
void display() {
System.out.println("Hi, display method");
}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}
}
Output – Hello Show Method
Hi, display method
this Keywords
Invoke current class constructor
class Demo {
Demo() {
System.out.println("Hello Mr. Abc");
}
Demo(int x) {
this();
System.out.println("x = "+x);
}
public static void main(String args[]) {
Demo d = new Demo(20);
}}
Output – Hello Mr. Abc
x = 20
To pass as an argument in the method
class Demo {
void show(Demo obj) {
System.out.println("Method Invoked");
}
void display() {
show(this);
}
public static void main(String args[]) {
Demo d = new Demo();
d.display();
}}
Output – Method Invoked
this Keywords
Actual Use of Constructor (Constructor Chaining)
class Demo {
int id, age;
String name;
Demo(int id, String name) {
this.id = id;
this.name = name;
}
Demo(int id, String name, int age) {
this(id, name);
this.age = age;
}
void display() {
System.out.println(id+"t"+name+"t"+age);
}
public static void main(String args[]) {
Demo d = new Demo(101,"Manish");
Demo d1 = new Demo(102,"Vishal",30);
d.display();
d1.display();
}}
Output – 101 Manish 0
102 Vishal 30
To prove this refer current class instance variable
class Demo {
void show() {
System.out.println(this);
}
public static void main(String args[]) {
Demo d = new Demo();
System.out.println(d);
d.show();
}
}
Output – Demo@15db9742
Demo@15db9742
Super keyword
 The super keyword in java refers to the object of immediate parent class. It means that when you create an
object of subclass then an object of base class is created implicitly, which is referred by super reference
variable.
 The super keyword basically used in inheritance.
 super keyword is used to refer immediate parent class instance variable.
class Test {
int age = 30;
}
class Demo extends Test {
int age = 20;
void show() {
System.out.println("Age in subclass = "+age);
System.out.println("Age in base class = "+super.age);
}
public static void main(String args[]) {
Demo d = new Demo();
d.show(); }}
Output - Age in subclass = 20
Age in base class = 30
Super keyword
 super keyword is used to refer immediate parent class method whenever you define a method with same in
both the class i.e. Parent and child class both have same name method.
class Test {
void display() {
System.out.println("display in base class");
}}
class Demo extends Test {
void display() {
System.out.println("display in sub class");
}
void show() {
super.display();
}
public static void main(String args[]) {
Demo d = new Demo();
d.show(); }}
Output - display in base class
Super keyword
 super keyword can also be used to access the parent class constructor. super keyword can call both
parametric and non-parametric constructors depending on the situation.
class Test {
Test() {
System.out.println("Base Class Constructor");
}
}
class Demo extends Test {
Demo() {
super();
System.out.println("Sub class Constructor");
}
public static void main(String args[]) {
Demo d = new Demo();
} }
Output - Base Class Constructor
Sub class Constructor
Super keyword
Important Points about super keyword
 super() must be the first statement in subclass class constructor.
 If a constructor does not explicitly call a base class constructor, the Java compiler automatically inserts a call
to the non-argument constructor of the base class. If the base class does not have a non-argument constructor,
you will get a compile-time error. class Test {
Test() {
System.out.println("Base Class Constructor");
}}
class Demo extends Test {
Demo() {
System.out.println("Sub class Constructor");
}
public static void main(String args[]) {
Demo d = new Demo();
}}
Output - Base Class Constructor
Sub class Constructor
static keyword
 In java, static keyword is mainly used for memory management.
 In order to create a static member, you need to precede its declaration with the static keyword.
 static keyword is a non-access modifier and can be used for the following:
 static block
 static variable
 static method
 static class
Static Block - In java static block is used to initialize static data member and it is executed before the main
method at the time of class loading. class Demo{
static {
System.out.println("Static Block");
}
public static void main(String args[]) {
System.out.println("Main Method");
}
}
Output - Static Block
Main Method
static keyword
Static Variable
 A variable declare with static keyword is called Static Variable.
 After declaration static variable, a single copy of the variable is created and divided among all objects at the
class level.
 Static variable can be created at class-level only and it gets memory only once in the class area at the time of
class loading.
 Static variable can’t re-initialized.
class Demo{
int e_id;
String name;
static String company = "PSIT";
Demo (int i, String n) {
e_id = i;
name = n;
}
void show() {
System.out.println("Emp_Id = "+e_id+"t Emp_Name = "+name+"t
Company ="+company);
}
public static void main(String args[]) {
Demo d = new Demo(101, "Manish");
Demo d1 = new Demo(102, "Vishal");
d.show();
d1.show();
}}
Output - Emp_Id = 101 Emp_Name = Manish Company =PSIT
Emp_Id = 102 Emp_Name = Vishal Company =PSIT
static keyword
Static Variable
static keyword
Static Method
 A method declared with static keyword is known as static method.
 The most common example of static method is main() method.
 Static method can be invoked directly i.e. no need to create an object of a class. So static method can be
invoked with class.
 Static method can access static data member only.
 this and super can not be used in static context.
static keyword
Static Method
Method call with class name
class Demo{
static int e_id = 101;
static String name = "Manish";
static void show() {
System.out.println("Emp_Id = "+e_id+"t Emp_Name
= "+name);
}
public static void main(String args[]) {
Demo.show();
}
}
Output - Emp_Id = 101 Emp_Name = Manish
Static data member can not access in static method
class Demo{
int e_id = 101;
static String name = "Manish";
static void show() {
System.out.println("Emp_Id = "+e_id+"t Emp_Name
= "+name);
}
public static void main(String args[]) {
Demo.show();
}
}
Output – Compile Time Error
(non-static variable e_id cannot be referenced from a
static context)
static keyword
Static Class
 A nested class can be static. Nested static class doesn’t need a reference of outer class.
 A static class cannot access non-static members of the outer class.
 You compile and run your nested class as usual that with outer class name.
Static class
class Demo{
static String name = "Manish";
static class NestedClass {
void show() {
System.out.println(" Emp_Name =
"+name);
}
}
public static void main(String args[]) {
Demo.NestedClass dns = new
Demo.NestedClass();
dns.show(); }
Output - Manish
final keyword
 The final keyword is used to make a variable as constant. That is if you make a variable as final, you cannot
change the value of that variable.
 A final variable with no value is called blank final variable. Blank final variable can be initialized in the
constructor only.
 Final keyword can be applied with following:
Variable - If you declare a variable with final keyword then it must be initialized.
Final Variable
class Demo {
final int x = 10;
void show() {
System.out.println(x);
}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
} }
Output - 10
Final Variable (Can’t change value)
class Demo {
final int x = 10;
void show() {
x = 20;
System.out.println(x);
}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}}
Output - error: cannot assign a value to final variable x
final keyword
Method - If you declare a method as final it means that you cannot override (Discuss in Inheritance) this method.
Final Method Cannot Override
class Test {
final void show() {
System.out.println("Parent Class Method");
}
}
class Demo extends Test{
void show(){
System.out.println("Cannot override due to final method.");}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}
}
Output - error: show() in Demo cannot override show() in Test
(Compile Time Error)
final keyword
Class - If you declare a class as final it means that you cannot inherit (Discuss in Inheritance) this class. That is,
you cannot use extends keyword.
Final Class cannot inherited
final class Test {}
class Demo extends Test{
void show(){
System.out.println("Cannot override due to final method.");
}
public static void main(String args[]) {
Demo d = new Demo();
d.show();
}
}
Output - error: cannot inherit from final Test
Note – Constructor cannot be declared as final because it is never inherited.
Finally
In java finally is a block that is used to execute important code such as closing connection, etc. Finally block is
always executed whether exception is handled or not.
Note – As finally used in Exception so it will be discussed later in Exception chapter.
finally {
// Statements;
}
Lecture   4_Java Method-constructor_imp_keywords

More Related Content

What's hot

Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
Christopher Akinlade
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Gousalya Ramachandran
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
JAINAM KAPADIYA
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
Class or Object
Class or ObjectClass or Object
Class or Object
Rahul Bathri
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
Eduardo Bergavera
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 

What's hot (20)

Generics in java
Generics in javaGenerics in java
Generics in java
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Java basic
Java basicJava basic
Java basic
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
class and objects
class and objectsclass and objects
class and objects
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Java unit2
Java unit2Java unit2
Java unit2
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 

Similar to Lecture 4_Java Method-constructor_imp_keywords

OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
Nagaraju Pamarthi
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
RAJASEKHARV10
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
MLG College of Learning, Inc
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
Kavitha713564
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Inheritance
InheritanceInheritance
Inheritance
Mavoori Soshmitha
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Java Methods
Java MethodsJava Methods
Java Methods
Rosmina Joy Cabauatan
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Keyword of java
Keyword of javaKeyword of java
Keyword of java
Jani Harsh
 
static methods
static methodsstatic methods
static methods
Micheal Ogundero
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 

Similar to Lecture 4_Java Method-constructor_imp_keywords (20)

OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Inheritance
InheritanceInheritance
Inheritance
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Java Methods
Java MethodsJava Methods
Java Methods
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Keyword of java
Keyword of javaKeyword of java
Keyword of java
 
static methods
static methodsstatic methods
static methods
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 

Recently uploaded

Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
ShivajiThube2
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 

Recently uploaded (20)

Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
JEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questionsJEE1_This_section_contains_FOUR_ questions
JEE1_This_section_contains_FOUR_ questions
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 

Lecture 4_Java Method-constructor_imp_keywords

  • 2. Contents  Java Methods  Command Line Arguments  Constructors  this Keyword  super Keyword  static Keyword  final Keyword  finally
  • 3. Java Methods  A java method is a set of statements that are used to perform some task.  Naming Convention –  Method name should start with lowercase letter.  If the method name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as getData().  Creating Method –  First you write return type of method then method name. void show() { // Statements; }  Method Calling – There are two ways in which method is called in java:  With return a value  With no return value
  • 4. Java Methods With Return a Value class Test { public static void main(String args []) { int c = show(); System.out.println(c); } int show() { int z = 10 + 20; return z; } } Output - 30 With No Return a Value class Test { public static void main(String args []) { Test t = new Test(); t.show(); } void show() { int z = 10 + 20; System.out.println(z); } } Output - 30
  • 5. Java Methods Passing parameters by value:  Passing Parameters by Value means calling a method with a parameter.  The order of passing value in calling and called method should be same. Passing Parameters by Value class Test { public static void main(String args []) { int x = 10, y = 20; Test t = new Test(); t.show(x, y); } void show(int x, int y) { int z = x + y; System.out.println(z); } } Output - 30
  • 6. Java Methods Method Overloading:  If a class has more than one method with same name but different parameters is known as Method Overloading.  Passing Parameters by Value means calling a method with a parameter.  There are ways to overload the method in java  By changing the number of arguments  By changing the data type
  • 7. Java Methods By changing number of arguments class Test { void show(int x, int y) { int z = x + y; System.out.println("z = "+z); } void show(int x, int y, int a) { int c = x + y + a; System.out.println("c = "+c); } public static void main(String args []) { int x = 10, y = 20, a = 30; Test t = new Test(); t.show(x, y); t.show(x, y, a); } } Output – z = 30 c = 60 By changing the data type class Test { void show(int x, int y) { int z = x + y; System.out.println("z = "+z); } void show(int x, int y, double a) { double c = x + y + a; System.out.println("c = "+c); } public static void main(String args []) { int x = 10, y = 20; double a = 30.5; Test t = new Test(); t.show(x, y); t.show(x, y, a); } } Output – z = 30 c = 60.5
  • 8. Command Line arguments  At runtime, when you will want to pass any information into a program then this is accomplished by passing command-Line arguments to main().  They are stored as strings in the String array passed to main( ). Command-Line Arguments public class Test { public static void main(String args[]) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); int sum = x+y; System.out.println("sum: " + sum); } } Execution Steps – javac Test.java java Test 10 20 Output – sum = 30
  • 9. Constructors  I java, Constructor is a special type of method. It is called at the time of object creation. Memory of the object is allocated at the time calling constructor.  Every class must have a constructor. If there is no constructor in class then java compiler automatically creates a default constructor. Compiler  It is used to initialize the object  Constructor has no return type except current class instance.  A constructor cannot be declared as final, static or synchronized.  A class can have more than one constructor i.e., constructor can be overloaded.  Constructor has the same name as class name. class Test { } class Test { Test() { } }
  • 10. Constructors  The default constructor is used to provide the default values to the object like zero (0), null, etc., depending on the data type. class Test{ int id; String name; void display(){ System.out.println(id+" "+name); } public static void main(String args[]){ Test s1=new Test(); Test s2=new Test(); s1.display(); s2.display(); } } Output – 0 null 0 null
  • 11. Constructors  In java, there are three types of constructor:  Parameterized Constructor  Non – Parametrized Constructor  Default Constructor Parameterized and Non-Parameterized Constructor A constructor has a specific parameter is called Parameterized Constructor. A constructor with no parameter is called Non-Parameterized Constructor.
  • 12. Constructors Parameterized Constructor class Test{ int id; String name; Test(int i, String n){ id = i; name = n; } void show(){ System.out.println("Id = "+id+"t"+"Name = "+name); } public static void main(String args[]){ Test t1=new Test(101, "Manish"); t1.show(); } } Output – Id = 101 Name = Manish Non-Parameterized Constructor class Test{ int id; String name; Test(){ id = 101; name = “Manish”; } void show(){ System.out.println("Id = "+id); System.out.println("Name = "+name); } public static void main(String args[]){ Test t1=new Test(); t1.show(); } } Output – Id = 101 Name = Manish
  • 13. Constructors  In java, there are three types of constructor:  Parameterized Constructor  Non – Parametrized Constructor  Default Constructor Parameterized and Non-Parameterized Constructor A constructor has a specific parameter is called Parameterized Constructor. A constructor with no parameter is called Non-Parameterized Constructor. Default Constructor Constructor generated by compiler if there is no constructor in program, that constructor is known as Default Constructor.
  • 14. Constructors Constructor Overloading Constructor Overloading means that a class having more than one constructor with different parameter. Constructor Overloading class Demo{ int id, salary; String name; Demo(int i, String n){ id = i; name = n; } Demo(int i, String n, int sal){ id = i; name = n; salary = sal; } void show(){ System.out.println("Id = "+id+"t"+"Name = "+name); } void show1(){ System.out.println("Id = "+id+"t"+"Name = "+name+"tSalary = "+salary); } public static void main(String args[]){ Demo t=new Demo(101, "Manish"); Demo t1=new Demo(102, "Manish", 2000); t.show(); t1.show1(); } } Output – Id = 101 Name = Manish Id = 102 Name = Manish Salary = 2000
  • 15. Constructors Constructor Vs. Method Java Constructor Java Method A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object. A constructor must not have a return type. A method must have a return type. The constructor is invoked implicitly. The method is invoked explicitly. The Java compiler provides a default constructor if you don't have any constructor in a class. The method is not provided by the compiler in any case. The constructor name must be same as the class name. The method name may or may not be same as the class name.
  • 16. this Keywords  In java, this is a reference variable that refers to the current class object.  this keyword is used to differentiate local and instance variable when both the variable name is same.  this() must be first statement in constructor.  To reuse the constructor from constructor is known as Constructor Chaining. Uses of this keyword  this keyword is used to call current class method.  this () is used to invoke current class constructor.  this can be passed as an argument in method and constructor call. this (Reference Variable) object
  • 17. this Keywords this keyword class Demo { int id; String name; Demo(int id, String name) { this.id = id; this.name = name; } void show() { System.out.println("ID = "+id+"t Name = "+name); } public static void main(String args[]) { Demo d = new Demo(101, "Manish"); d.show(); } } Output – Id = 101 Name = Manish Used to call current class method class Demo { void show() { System.out.println("Hello Show Method"); this.display(); // this.display() is same as display() } void display() { System.out.println("Hi, display method"); } public static void main(String args[]) { Demo d = new Demo(); d.show(); } } Output – Hello Show Method Hi, display method
  • 18. this Keywords Invoke current class constructor class Demo { Demo() { System.out.println("Hello Mr. Abc"); } Demo(int x) { this(); System.out.println("x = "+x); } public static void main(String args[]) { Demo d = new Demo(20); }} Output – Hello Mr. Abc x = 20 To pass as an argument in the method class Demo { void show(Demo obj) { System.out.println("Method Invoked"); } void display() { show(this); } public static void main(String args[]) { Demo d = new Demo(); d.display(); }} Output – Method Invoked
  • 19. this Keywords Actual Use of Constructor (Constructor Chaining) class Demo { int id, age; String name; Demo(int id, String name) { this.id = id; this.name = name; } Demo(int id, String name, int age) { this(id, name); this.age = age; } void display() { System.out.println(id+"t"+name+"t"+age); } public static void main(String args[]) { Demo d = new Demo(101,"Manish"); Demo d1 = new Demo(102,"Vishal",30); d.display(); d1.display(); }} Output – 101 Manish 0 102 Vishal 30 To prove this refer current class instance variable class Demo { void show() { System.out.println(this); } public static void main(String args[]) { Demo d = new Demo(); System.out.println(d); d.show(); } } Output – Demo@15db9742 Demo@15db9742
  • 20. Super keyword  The super keyword in java refers to the object of immediate parent class. It means that when you create an object of subclass then an object of base class is created implicitly, which is referred by super reference variable.  The super keyword basically used in inheritance.  super keyword is used to refer immediate parent class instance variable. class Test { int age = 30; } class Demo extends Test { int age = 20; void show() { System.out.println("Age in subclass = "+age); System.out.println("Age in base class = "+super.age); } public static void main(String args[]) { Demo d = new Demo(); d.show(); }} Output - Age in subclass = 20 Age in base class = 30
  • 21. Super keyword  super keyword is used to refer immediate parent class method whenever you define a method with same in both the class i.e. Parent and child class both have same name method. class Test { void display() { System.out.println("display in base class"); }} class Demo extends Test { void display() { System.out.println("display in sub class"); } void show() { super.display(); } public static void main(String args[]) { Demo d = new Demo(); d.show(); }} Output - display in base class
  • 22. Super keyword  super keyword can also be used to access the parent class constructor. super keyword can call both parametric and non-parametric constructors depending on the situation. class Test { Test() { System.out.println("Base Class Constructor"); } } class Demo extends Test { Demo() { super(); System.out.println("Sub class Constructor"); } public static void main(String args[]) { Demo d = new Demo(); } } Output - Base Class Constructor Sub class Constructor
  • 23. Super keyword Important Points about super keyword  super() must be the first statement in subclass class constructor.  If a constructor does not explicitly call a base class constructor, the Java compiler automatically inserts a call to the non-argument constructor of the base class. If the base class does not have a non-argument constructor, you will get a compile-time error. class Test { Test() { System.out.println("Base Class Constructor"); }} class Demo extends Test { Demo() { System.out.println("Sub class Constructor"); } public static void main(String args[]) { Demo d = new Demo(); }} Output - Base Class Constructor Sub class Constructor
  • 24. static keyword  In java, static keyword is mainly used for memory management.  In order to create a static member, you need to precede its declaration with the static keyword.  static keyword is a non-access modifier and can be used for the following:  static block  static variable  static method  static class Static Block - In java static block is used to initialize static data member and it is executed before the main method at the time of class loading. class Demo{ static { System.out.println("Static Block"); } public static void main(String args[]) { System.out.println("Main Method"); } } Output - Static Block Main Method
  • 25. static keyword Static Variable  A variable declare with static keyword is called Static Variable.  After declaration static variable, a single copy of the variable is created and divided among all objects at the class level.  Static variable can be created at class-level only and it gets memory only once in the class area at the time of class loading.  Static variable can’t re-initialized. class Demo{ int e_id; String name; static String company = "PSIT"; Demo (int i, String n) { e_id = i; name = n; } void show() { System.out.println("Emp_Id = "+e_id+"t Emp_Name = "+name+"t Company ="+company); } public static void main(String args[]) { Demo d = new Demo(101, "Manish"); Demo d1 = new Demo(102, "Vishal"); d.show(); d1.show(); }} Output - Emp_Id = 101 Emp_Name = Manish Company =PSIT Emp_Id = 102 Emp_Name = Vishal Company =PSIT
  • 27. static keyword Static Method  A method declared with static keyword is known as static method.  The most common example of static method is main() method.  Static method can be invoked directly i.e. no need to create an object of a class. So static method can be invoked with class.  Static method can access static data member only.  this and super can not be used in static context.
  • 28. static keyword Static Method Method call with class name class Demo{ static int e_id = 101; static String name = "Manish"; static void show() { System.out.println("Emp_Id = "+e_id+"t Emp_Name = "+name); } public static void main(String args[]) { Demo.show(); } } Output - Emp_Id = 101 Emp_Name = Manish Static data member can not access in static method class Demo{ int e_id = 101; static String name = "Manish"; static void show() { System.out.println("Emp_Id = "+e_id+"t Emp_Name = "+name); } public static void main(String args[]) { Demo.show(); } } Output – Compile Time Error (non-static variable e_id cannot be referenced from a static context)
  • 29. static keyword Static Class  A nested class can be static. Nested static class doesn’t need a reference of outer class.  A static class cannot access non-static members of the outer class.  You compile and run your nested class as usual that with outer class name. Static class class Demo{ static String name = "Manish"; static class NestedClass { void show() { System.out.println(" Emp_Name = "+name); } } public static void main(String args[]) { Demo.NestedClass dns = new Demo.NestedClass(); dns.show(); } Output - Manish
  • 30. final keyword  The final keyword is used to make a variable as constant. That is if you make a variable as final, you cannot change the value of that variable.  A final variable with no value is called blank final variable. Blank final variable can be initialized in the constructor only.  Final keyword can be applied with following: Variable - If you declare a variable with final keyword then it must be initialized. Final Variable class Demo { final int x = 10; void show() { System.out.println(x); } public static void main(String args[]) { Demo d = new Demo(); d.show(); } } Output - 10 Final Variable (Can’t change value) class Demo { final int x = 10; void show() { x = 20; System.out.println(x); } public static void main(String args[]) { Demo d = new Demo(); d.show(); }} Output - error: cannot assign a value to final variable x
  • 31. final keyword Method - If you declare a method as final it means that you cannot override (Discuss in Inheritance) this method. Final Method Cannot Override class Test { final void show() { System.out.println("Parent Class Method"); } } class Demo extends Test{ void show(){ System.out.println("Cannot override due to final method.");} public static void main(String args[]) { Demo d = new Demo(); d.show(); } } Output - error: show() in Demo cannot override show() in Test (Compile Time Error)
  • 32. final keyword Class - If you declare a class as final it means that you cannot inherit (Discuss in Inheritance) this class. That is, you cannot use extends keyword. Final Class cannot inherited final class Test {} class Demo extends Test{ void show(){ System.out.println("Cannot override due to final method."); } public static void main(String args[]) { Demo d = new Demo(); d.show(); } } Output - error: cannot inherit from final Test Note – Constructor cannot be declared as final because it is never inherited.
  • 33. Finally In java finally is a block that is used to execute important code such as closing connection, etc. Finally block is always executed whether exception is handled or not. Note – As finally used in Exception so it will be discussed later in Exception chapter. finally { // Statements; }