Core Java by Mahika Tutorials - PowerPoint PPT Presentation

View by Category
About This Presentation
Title:

Core Java by Mahika Tutorials

Description:

Mahika Tutorials here sharing core java tutorial PPT file. You can visit our YouTube page for video tutorial – PowerPoint PPT presentation

Number of Views:51
Date added: 29 June 2020
Slides: 123
Provided by: MahikaTutorials

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: Core Java by Mahika Tutorials


1
Core Java
checked exception
2
Programming Languages
Low-Level Languages (Machine dependent)
High Level Languages (Machine independent)
Assembly language
Machine(Binary) language
3
  • Java
  • Java was created by James Gosling at Sun
    Microsystems (which is now acquired by Oracle
    Corporation) and released in 1995.
  • Java is a high level, object-oriented programming
    language.

4
(No Transcript)
5
OOPs Concepts
6
  • Encapsulation
  • Binding (or wrapping) code and data together into
    a single unit.
  • A java class is the example of encapsulation.

7
  • Abstraction
  • Hiding internal details and showing functionality
    only.

WithoutAbstraction
With Abstraction
8
  • Inheritance
  • A mechanism by which a class acquires all the
    properties and behaviours of an existing class.
  • Provides code reusability.
  • Used to achieve runtime polymorphism.

9
  • Polymorphism
  • Ability to take multiple forms.

Example- int a10,b20,c cab
//addition String firstnameSachin,
lastnameTendulkar, fullname fullnamefirstname
lastname//concatenation
10
Java supports primitive data types , hence it is
a fully OOPL but not pure OOPL. int i20
//primitive type Integer anew Integer(20)
//Class type
11
Core Java
12
  • Java Version History
  • JDK Alpha and Beta (1995)
  • JDK 1.0 (23rd Jan, 1996)
  • JDK 1.1 (19th Feb, 1997)
  • J2SE 1.2 (8th Dec, 1998)
  • J2SE 1.3 (8th May, 2000)
  • J2SE 1.4 (6th Feb, 2002)
  • J2SE 5.0 (30th Sep, 2004)
  • Java SE 6 (11th Dec, 2006)
  • Java SE 7 (28th July, 2011)
  • Java SE 8 (18th March, 2014)
  • Java SE 9 (September 2017)

13
Signature of main()
14
public static void main(String args)
.. ..
15
returnType methodName(arguments)
int m3(int n) .. return nn
void m1() .. ..
int m2() .. return 2
16
public static void main(String args)
.. ..
17
Invoking Member Funtions Of A Class
class Test public static void myStatic()
----- -----
----- public void myNonStatic()
-----
class Sample public void CallerFunction()
// Invoking static function
Test.myStatic() // Invoking non-static
function Test t new Test()
t.myNonStatic()
18
Invoking main()
class Test public static void
main(String args) -----
----- -----
// Incase of static main()
Test.main()
// Incase of non-static main() Test
tnew Test() t.main()
  • Since the main method is static Java virtual
    Machine can call it without creating any instance
    of a class which contains the main method.

19
Thank You
20
  • Secured
  • Java is secured because
  • No explicit pointer
  • Java Programs run inside virtual machine sandbox
  • Exception handling concept

21
  • Valid java main method signature
  • public static void main(String args)  
  • public static void main(String args)  
  • public static void main(String args)  
  • public static void main(String... args)  
  • static public void main(String args)  
  • public static final void main(String args)  
  • final public static void main(String args)  
  • final strictfp public static void main(String ar
    gs)  

22
(No Transcript)
23
  • JVM
  • JVM (Java Virtual Machine) is an abstract
    machine. It is a specification that provides
    runtime environment in which java bytecode can be
    executed.
  • JVM is the engine that drives the java code
  • The JVM performs following main tasks
  • Loads code
  • Verifies code
  • Executes code

24
  • JRE
  • JRE is an acronym for Java Runtime Environment.

25
  • JDK
  • JDK is an acronym for Java Development Kit.
  • Includes a complete JRE (Java Runtime
    Environment) plus tools for developing,
    debugging, and monitoring Java applications. 

26
Internal Architecture of JVM
Memory areas allocated by JVM
27
Internal Architecture of JVM
Memory areas allocated by JVM
28
Java Keywords
  • Words that cannot be used as identifiers in
    programs.
  • There are 50 java keywords.
  • All keywords are in lower-case.
  • Each keyword has special meaning for the
    compiler.
  • Keywords that are not used in Java so far are
    called reserved words.

29
List of Java Keywords
Category Keywords
Access modifiers private, protected, public
Class, method, variable modifiers abstract, class, extends, final, implements, interface, native,new, static, strictfp, synchronized, transient, volatile
Flow control break, case, continue, default, do, else, for, if, instanceof,return, switch,while
Package control import, package
Primitive types boolean, byte, char, double, float, int, long, short
Exception handling assert, catch, finally, throw, throws, try
Enumeration enum
Others super, this, void
Unused const, goto
  • Points to remember
  • const and goto are resevered words.
  • true, false and null are literals, not keywords.

30
Java Identifiers
  • Names given to programming elements like
    variables, methods, classes, packages and
    interfaces.

Rules for Naming Java Identifiers
  • Allowed characters for identifiers areA-Z,
    a-z,0-9, (dollar sign) and _
    (underscore).
  • Should not start with digits(0-9).
  • Case-sensitive, like id and ID are different.
  • Java keyword cannot be used as an identifier.

31
Java Naming conventions
Name Convention
class name should start with uppercase letter and be a noun e.g.Shape, String, Color, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Clonable etc.
method name should start with lowercase letter and be a verb e.g. compute(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, lastName etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. BLUE, MAX_PRIORITY etc.
32
Core Java
33
  • Class
  • A template that describes the data and behavior.
  • Object
  • An entity that has state and behavior is known as
    an object e.g. chair, bike, table, car etc.
  • state represents data (value) of an object.
  • behavior represents the functionality of an
    object such as deposit, withdraw etc.

34
Data members id name
Student
class
Methods setId() setName() getId() getName()
35
Java class example
public class Student private int id
private String name public int getId()
return id public void setId(int
id) this.id id public
String getName() return name
public void setName(String name)
this.name name
36
Instantiation/ Object Creation- Classname
referenceVariablenew Classname() e.g.- Student
snew Student() Method Invocation/Call- Non-sta
tic method referenceVariable.methodname() e.g.-
s.show() static method Classname.methodname()
e.g.- Sample.display()
37
  • Scanner class
  • A class in java.util package
  • Used for obtaining the input of the primitive
    types like int, double etc. and strings
  • Breaks its input into tokens using a delimiter
    pattern, which by default matches whitespace. 
  • 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.

38
Creating instance of Scanner class To read
from System.in Scanner sc new
Scanner(System.in) To read from File Scanner
sc new Scanner(new File("myFile"))
39
Commonly used methods of Scanner class
Method Description
public String next() it returns the next token from the scanner.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double nextDouble() it scans the next token as a double value.
40
Thank You
41
Types of Variable
local
instance
static
42
  • public class Student
  • int rn //instance variable
  • String name //instance variable
  • static String college //static variable
  • void m1()
  • int l //local variable
  • .

43
class Student    int id    
String name  static String
collegeSVC       public static void ma
in(String args)      Student s1new Studen
t()      Student s2new Student()  

Class Area
collegeSVC
id2name Anil
s2
id1name Hriday
s1
Stack
Heap
44
Thank You
45
class Student    int id    String name       vo
id insertRecord(int i, String n)  //method    
 idi      namen           void displayInf
ormation() System.out.println(id" "name)//met
hod       public static void main(String args) 
    Student s1new Student()     Student s2new S
tudent()        s1.insertRecord(1,Hriday")     
s2.insertRecord(2,Anil")        s1.displayInform
ation()     s2.displayInformation()           
 
46
(No Transcript)
47
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
lowest unicode value\u0000
highest unicode value\uFFFF
48
  • Operators
  • Assignment Operator  
  • Arithmetic Operators - / --  
  • Relational Operators gt lt gt lt !  
  • Logical Operators !
  • Compound Assignment Operators - /  
  • Conditional Operator ?

49
  • Control Structures
  • Conditional
  • Simple if
  • ifelse
  • if-else-if ladder
  • Nested if
  • switch case
  • Looping
  • while loop
  • for loop
  • do while loop
  • for each/enhanced for loop

50
if Statement
  • if(condition)  
  • //code to be executed  
  •   

51
if else Statement
  • if(condition)  
  • //code if condition is true  
  • else  
  • //code if condition is false  
  •   

52
if-else-if ladder Statement
  • if(condition1)  
  • //code to be executed if condition1 is true  
  • else if(condition2)  
  • //code to be executed if condition2 is true  
  •   
  • else if(condition3)  
  • //code to be executed if condition3 is true  
  •   
  • ...  
  • else  
  • //code to be executed if all the conditions are
     false  
  •   

53
Nested if
if(Boolean_expression 1) // Executes when
the Boolean expression 1 is true
if(Boolean_expression 2) //
Executes when the Boolean expression 2 is true

54
Core Java
55
switch Statement
Expression
  • switch(expression)    
  • case value1    
  •  //code to be executed    
  •   break  //optional  
  • case value2    
  •   //code to be executed    
  •   break  //optional  
  • ......    
  •     
  • default     
  • //code to be executed if all cases are not ma
    tched    
  •     

case 1?
Case Block 1
Yes
No
case 2?
Yes
Case Block 2
No
case 3?
Case Block 3
Yes
No
default Block
56
  • switch Statement
  • Expression can be byte, short, char, and int.
  • From JDK7 onwards, it also works with enumerated
    types ( Enums in java), the String class
    and Wrapper classes.
  • Duplicate case values are not allowed.
  • switch(ch)
  • case 1 .......
  • break
  • case 1 ......
  • break

57
  • The value for a case must be the same data type
    as the variable in the switch.
  • switch(ch)
  • case 1 ......
  • break
  • case 2 ......
  • break
  • The value for a case must be a constant or a
    literal.Variables are not allowed.

58
  • The break statement is used inside the switch to
    terminate a statement sequence.
  • The break statement is optional. If omitted,
    execution will continue on into the next case.
  • The default statement is optional.

59
while Loop
  • while(condition)  
  • //code to be executed  
  •   

60
do-while Loop
  • do  
  • //code to be executed  
  • while(condition) 

61
for Loop
  • for(initializationconditionincr/decr)  
  • //code to be executed  
  •   

62
  • break Statement
  • Used to break loop or switch statement.

63
  • continue Statement
  • Used to continue loop.
  • Skips the remaining code at specified condition.

64
Polymorphism
Compile-time Polymorphism
Run-time Polymorphism
Method Overriding
Method Overloading
65
  • Method Overloading
  • When a class have multiple methods by same name
    but different parameters.
  • Advantage
  • Increases the readability of the program.
  • Different ways to overload the method
  • By changing number of arguments
  • By changing the data type of arguments
  • Method Overloading is not possible by changing
    the return type or access specifier of a method.

66
  • Method Overloading by changing the no. of
    arguments
  • class Calculation  
  • void sum(int a,int b)
  • System.out.println(ab)
  •   
  •   void sum(int a,int b,int c)
  • System.out.println(abc)
  •   
  •   
  •   public static void main(String args)  
  •   Calculation objnew Calculation()  
  •   obj.sum(40,10,10)  
  •   obj.sum(50,20)  
  •   
  •     
  •   

67
  • Method Overloading by changing data type of
    argument
  • class Calculation
  •   
  •   void sum(int a,int b)
  • System.out.println(sum of int (ab))
  •   
  •   void sum(double a,double b)
  • System.out.println((sum of double (ab))
  •   
  •   
  •   public static void main(String args)  
  •   Calculation objnew Calculation()  
  •   obj.sum(19.5,10.5)  
  •   obj.sum(12,20)  
  •   

68
  • Overloading Main method
  • class Test  
  •   public static void main(int a)  
  •   System.out.println(a)  
  •     
  •     
  •   public static void main(String args)  
  •   System.out.println("main() method invoked")  
  •   main(10)  
  •     
  •   

69
  • Method Overloading and Type Promotion

70
  • If we have overloaded methods with one
    byte/short/int/long parameter then always method
    with int is called.
  • To invoke method with long parameter L should be
    append to the value while calling
  • Method with byte/short is called only if we pass
    the variable of that type or we typecast the
    value.
  • If we have overloaded method with one
    int/float/double and we pass long value then
    method with int parameter is called.
  • If we have overloaded method with one
    float/double and we pass long value then method
    with float parameter is called.

71
  • Ambiguity in Method Overloading
  • class Test  
  •   void sum(int a,long b)System.out.println(ab)
  •   void sum(long a,int b)System.out.println(ab)
      
  •   
  •   public static void main(String args)  
  •    Test  objnew  Test()  
  •   obj.sum(20,20)// ambiguity  
  •     
  •   
  • OutputCompile Time Error

72
  • Constructor
  • Special type of method that is used to initialize
    the object.
  • Invoked at the time of object creation. 
  • Can be overloaded.
  • Rules for creating java constructor
  • Constructor name must be same as its class name
  • Constructor must have no explicit return type
  • Types of java constructors
  • Default constructor (no-arg constructor)
  • Parameterized constructor

73
  • If there is no constructor in a class, compiler
    automatically creates a default constructor.

74
  • class Student  
  • int id  
  • String name  
  •   
  • void display()System.out.println(id" "name)  
  •   
  • public static void main(String args)  
  • Student s1new Student()  
  • Student s2new Student()  
  • s1.display()  
  • s2.display()  
  •   
  •   

75
  • Parameterized constructor
  • Used to provide different values to the distinct
    objects.
  • Example
  • class Student
  • int id
  • String name
  • Student(int i,String n)
  • id i
  • name n
  • void display()System.out.println(id"
    "name)
  • public static void main(String args)
  • Student s1 new Student(1,abc")
  • Student s2 new Student(2,xyz")
  • s1.display()
  • s2.display()

76
  • Java Copy Constructor
  • There is no copy constructor in java. But, we can
    copy the values of one object to another like
    copy constructor in C.
  • There are many ways to copy the values of one
    object into another in java.
  • They are
  • By constructor
  • By assigning the values of one object into
    another
  • By clone() method of Object class

77
  • In this example, we are going to copy the values
    of one object into another using java
    constructor.
  • class Student6
  • int id
  • String name
  • Student6(int i,String n)
  • id i
  • name n
  • Student6(Student6 s)
  • id s.id
  • name s.name
  • void display()System.out.println(id"
    "name)
  • public static void main(String args)
  • Student6 s1 new Student6(111,"Karan")
  • Student6 s2 new Student6(s1)
  • s1.display()

78
  • Copying values without constructor
  • class Student7
  • int id
  • String name
  • Student7(int i,String n)
  • id i
  • name n
  • Student7()
  • void display()System.out.println(id"
    "name)
  • public static void main(String args)
  • Student7 s1 new Student7(111,"Karan")
  • Student7 s2 new Student7()
  • s2.ids1.id
  • s2.names1.name
  • s1.display()
  • s2.display()

79
  • static keyword
  • static is a non-access modifier.
  • Used for memory management mainly.
  • The static can be
  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class

80
  • static variable
  • Used to refer the common property of all objects
    e.g. company name of employees,college name of
    students etc.
  • Gets memory only once in class area at the time
    of class loading.
  • Local variables cannot be static.
  • Advantage
  • It makes your program memory efficient (i.e it
    saves memory).

81
  • //Program for static variable  
  •   
  • class Student  
  •    int id  
  •    String name  
  •    static String college SVC"  
  •      
  •    Student(int i,String n)  
  •     idi  
  •     name  n  
  •      
  •  void display ()
  • System.out.println(id" "name" "college)  
  •   
  •  public static void main(String args)  
  •  Student s1  new Student(1,Hriday")  
  •  Student s2  new Student(2,Anil")  
  •    

Class Area
collegeSVC
id2name Anil
s2
id1name Hriday
s1
Stack
Heap
82
  • static method
  • Method defined with the static keyword.
  • Belongs to the class rather than object of a
    class.
  • Can be invoked without the need for creating an
    instance of a class.
  • Can access static data members and can change the
    value of it.
  • Cannot use non static data member or call
    non-static method directly.
  • this and super cannot be used in static context.

83
  • static block
  • Used to initialize the static data member.
  • Is executed before main method at the time of
    classloading.
  • Example
  • class A
  • static
  • System.out.println("static block invoked")
  • public static void main(String args)
  • System.out.println(main invoked")

84
  • Can we execute a program without main() method?
  • Yes, one of the way is static block but in
    previous version of JDK not in JDK 1.7.
  • class A3  
  •   static  
  •   System.out.println("static block is invoked")  
  •   System.exit(0)  
  •     
  •   

85
  • this keyword in java
  • A reference variable that refers to the current
    object.
  • Usage of this keyword
  • this keyword can be used to refer current class
    instance variable.
  • this() can be used to invoke current class
    constructor.
  • this can be used to invoke current class method
    (implicitly)
  • this can be used to return the current class
    instance from the method.
  • this can be passed as an argument in the method
    call.
  • this can be passed as argument in the constructor
    call.

86
  • this() to invoke current class constructor
  • Used for constructor chaining.
  • Used to reuse the constructor.
  • Call to this() must be the first statement in
    constructor.
  • Syntax
  • this() // call default constructor
  • this(value1,value2,.....) //call parametrized
    constructor

87
//this() to invoke current class
constructor public class Rectangle private
int x, y private int width, height
public Rectangle() this(0, 0, 0, 0)
public Rectangle(int width, int height)
this(0, 0, width, height)
public Rectangle(int x, int y, int width, int
height) this.x x this.y
y this.width width
this.height height .
88
  • this to invoke current class method (implicitly)
  • Can be used to invoke method of the current
    class.
  • If you don't use the this keyword, compiler
    automatically adds this keyword while invoking
    the method. 

89
  • this keyword used to refer current class instance
    variable
  • class Student
  • int id
  • String name
  • Student(int id,String name)
  • this.id id
  • this.name name
  • void display()System.out.println(id"
    "name)
  • public static void main(String args)
  • Student s1 new Student(1,Hriday")
  • Student s2 new Student(2,"Anil")
  • s1.display()
  • s2.display()

90
  • this() constructor call (constructor chaining)
  • class Student
  • int id
  • String name
  • Student ()System.out.println("default
    constructor invoked")
  • Student(int id,String name)
  • this ()//it is used to invoke current
    class constructor.
  • this.id id
  • this.name name
  • void display()System.out.println(id"
    "name)
  • public static void main(String args)
  • Student s1 new Student(1,Hriday")
  • Student s2 new Student(2,"Anil")
  • s1.display()
  • s2.display()

91
this to pass as an argument in the method
class Test     int a     int
b           Test()              a
40         b 60                // Method
that receives 'this' keyword as
parameter     void display(Test
obj)              System.out.println("a " a
"  b " b)             // Method that
pases current class instance     void
get()              display(this)            pub
lic static void main(String args)              
Test object new Test()         object.get()   
   Output- a40 b60
92
Core Java
93
this to pass as argument in the constructor call
class B     A obj     B(A obj)
       this.objobj          void display()  
    System.out.println(obj.data)
//10           
class A     int data10      A()      
 B bnew B(this)       b.display()          p
ublic static void main(String args)     
 A anew A()          
94
  • this keyword in java
  • A reference variable that refers to the current
    object.
  • Usage of this keyword
  • this keyword can be used to refer current class
    instance variable.
  • this() can be used to invoke current class
    constructor.
  • this can be used to invoke current class method
    (implicitly)
  • this can be used to return the current class
    instance from the method.
  • this can be passed as an argument in the method
    call.
  • this can be passed as argument in the constructor
    call.
  • this keyword cannot be used in static context.

95
  • Inheritance
  • A mechanism in which one object acquires all the
    properties and behaviors of parent object.
  • Represents the IS-A relationship, also known
    as parent-child relationship
  • extends keyword indicates that you are making a
    new class that derives from an existing class.
  • The meaning of "extends" is to increase the
    functionality.
  • A class which is inherited is called parent or
    super class and the new class is called child or
    subclass.
  • Inheritance in java is used
  • For Method Overriding (so runtime polymorphism
    can be achieved).
  • For Code Reusability.
  • Syntax of Java Inheritance
  • class Subclass-name extends Superclass-name
  • //methods and fields

96
Types of inheritance in java
Multiple inheritance is not supported in java
through class
97
Object class
  • Object class is the superclass of all the classes
    in java by default.
  • Every class in Java is directly or indirectly
    derived from the Object class.
  • Object class is present in java.lang package.

class A ..
class A extends Object ..
98
Object class
class A extends Object .. class B extends
A .
class A . class B extends A .
99
Commonly used Methods of Object class
Method Description
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
100
Single Inheritance
101
Multilevel Inheritance
102
Hierarchical Inheritance
103
Multiple Inheritance
  • A feature where a class can inherit properties of
    more than one parent class.
  • Java doesnt allow multiple inheritance by using
    classes ,for simplicity and to avoid the
    ambiguity caused by it.
  • It creates problem during various operations like
    casting, constructor chaining etc.

104
Multiple Inheritance and Ambiguity
class A    void show()
System.out.println("Hello")  
   class B    void show()
System.out.println("Welcome")      
class C extends A,B //suppose if it was
allowed       public static void main(String ar
gs)        C objnew C()      
obj.show() //ambiguity        
105
Multiple Inheritance and Diamond Problem
106
Multiple inheritance in Java by interface
  • If a class implements multiple interfaces, or an
    interface extends multiple interfaces.

107
Polymorphism
Compile-time Polymorphism
Run-time Polymorphism
Method Overriding
Method Overloading
108
  • Method Overriding
  • If subclass (child class) has the same method as
    declared in the parent class, it is known as
    method overriding in java.
  • Usage
  • Used to provide specific implementation of a
    method that is already provided by its super
    class.
  • Used for runtime polymorphism

Example
class Vehicle   void run()System.out.println("Ve
hicle is running")      class Bike extends Vehi
cle   void run()System.out.println("Bike is runn
ing )      public static void main(String args
)   Bike obj  new Bike()   obj.run()     
109
At compile-time
class Shape void draw()
System.out.println("No Shape") class
Rectangle extends Shape void draw()
System.out.println("Drawing rectangle")
class Circle extends Shape void
draw() System.out.println("Drawing
circle") class Triangle extends
Shape void draw()
System.out.println("Drawing circle")
public class Test public static void
main(String args) Shape s
snew Shape() s.draw() s new
Circle() s.draw() snew
Rectangle() s.draw() snew
Triangle() s.draw()
110
At run-time
class Shape void draw()
System.out.println("No Shape") class
Circle extends Shape void draw()
System.out.println("Drawing circle")
class Rectangle extends Shape void
draw() System.out.println("Drawing
rectangle") class Triangle extends
Shape void draw()
System.out.println("Drawing circle")
public class Test public static void
main(String args) Shape s
snew Shape() s.draw() s new
Circle() s.draw() snew
Rectangle() s.draw() snew
Triangle() s.draw()
111
  • Rules for Method Overriding
  • Method must have same name as in the parent class
  • Method must have same parameter as in the parent
    class.
  • Method must have same return type(or sub-type). 
  • Must be IS-A relationship (inheritance).
  • private method cannot be overridden.
  • final method cannot be overridden
  • static method cannot be overridden because
    static method is bound with class whereas
    instance method is bound with object.
  • We can not override constructor as parent and
    child class can never have constructor with same
    name.
  • Access Modifier of the overriding method (method
    of subclass) cannot be more restrictive than the
    overridden method of parent class.
  • Binding of overridden methods happen at runtime
    which is known as dynamic binding.

112
  • class Test2  
  • public static void main(String args)  
  • SBI snew SBI()  
  • ICICI inew ICICI()  
  • AXIS anew AXIS()  
  • System.out.println("SBI Rate of Interest "s.getR
    ateOfInterest())  
  • System.out.println("ICICI Rate of Interest "i.ge
    tRateOfInterest())  
  • System.out.println("AXIS Rate of Interest "a.get
    RateOfInterest())  
  •   
  •   
  • //Method overriding
  • class Bank  
  • int getRateOfInterest()return 0  
  •   
  •   
  • class SBI extends Bank  
  • int getRateOfInterest()return 8  
  •   
  •   
  • class ICICI extends Bank  
  • int getRateOfInterest()return 7  
  •   
  • class AXIS extends Bank  
  • int getRateOfInterest()return 9  
  •   
  •   

113
  • ExceptionHandling with MethodOverriding in Java
  • If the superclass method does not declare an
    exception, subclass overridden method cannot
    declare the checked exception.

class Child extends Parent  
void msg()throws IOException        
System.out.println(child")  
      public static void main(Strin
g args)      
 Parent pnew Child()     
 p.msg()           
class Parent   void msg()
System.out.println("parent")
     
OutputCompile Time Error
114
  •  If the superclass method does not declare an
    exception, subclass overridden method cannot
    declare the checked exception but can declare
    unchecked exception.

class Parent      void msg()
System.out.println("parent")
        
class Child extends Parent     
void msg()throws ArithmeticException
        System.out.println("child")    
       public static void main(String args)
       Parent pnew Child()      
p.msg()           
Outputchild
115
  • If the superclass method declares an exception,
    subclass overridden method can declare same,
    subclass exception or no exception but cannot
    declare parent exception.

class Child extends Parent     
void msg()throws Exception
System.out.println("child")
      public static void main(String 
args)       
Parent pnew Child()  
try      
p.msg()      
catch(Exception e)
           
class Parent      void msg()throws Arithme
ticException
System.out.println("parent")
        
OutputCompile Time Error
116
Example in case subclass overridden method
declares subclass exception
class Parent void msg()throws
Exception
System.out.println("parent")
Class Child extends Parent void
msg()throws ArithmeticException
System.out.println("child")
public static void main(String args)
Parent pnew Child()
try
p.msg()
catch(Exception e)
Outputchild
117
  • Covariant Return Type
  • Specifies that the return type may vary in the
    same direction as the subclass.
  • Since Java5, it is possible to override method by
    changing the return type if subclass overrides
    any method, but it changes its return type to
    subclass type.

class ShapeFactory public Shape newShape()
class CircleFactory extends
ShapeFactory public Circle newShape()

class Shape class Circle extends
Shape
118
  • super keyword
  • A reference variable that is used to refer
    immediate parent class object.
  • super keyword cannot be used in static context.
  • Usage
  • super is used to refer immediate parent class
    instance variable.
  • super() is used to invoke immediate parent class
    constructor,.
  • super is used to invoke immediate parent class
    method.

119
super used to refer immediate parent class
instance variable class Vehicle     int speed7
0         class Bike extends Vehicle     int sp
eed100            void display()      System.ou
t.println(super.speed)// Vehicle speed 
System.out.println(speed)// Bike
speed            public static void main(String a
rgs)      Bike bnew Bike()      b.display() 
             
120
super() to invoke parent class
constructor class Vehicle
Vehicle()System.out.println("Vehicle created")
class Bike extends Vehicle Bike()
super()//invokes parent class constructor
System.out.println("Bike created")
public static void main(String args)
Bike bnew Bike()
121
super() to invoke parent class constructor
  • If used, super() must be the first statement
    inside the constructor, hence either super() or
    this() can be used inside the constructor.
  • super() is added in each class constructor
    automatically by compiler if there is no super()
    or this().

122
super used to invoke parent class method class
Vehicle void show()System.out.println("Vehi
cle Runing") class Bike extends
Vehicle void show()System.out.println("Bike
Runing ") void display()
super.show() show() public static
void main(String args) Bike bnew
Bike() b.display()
123
  • final Keyword
  • Used to restrict the user.
  • final can be
  • Variable?If you make any variable as final, you
    cannot change the value of final variable(It will
    be constant).
  • Method-gtIf you make any methode as final, you
    cannot override it.
  • Class-gtIf you make any class as final, you cannot
    extend it.

124
  • //final method
  • class Bike  
  •   final void run()System.out.println("running")
      
  •   
  •      
  • class Honda extends Bike  
  •    void run()System.out.println("running safely w
    ith 100kmph")  
  •      
  •    public static void main(String args)  
  •    Honda honda new Honda()  
  •    honda.run()  
  •      
  •   
  • OutputCompile Time Error
  • //final variable
  • class Bike9  
  •  final int speedlimit90//final variable  
  •  void run()  
  •   speedlimit400  
  •    
  •  public static void main(String args)  
  •  Bike9 objnew  Bike9()  
  •  obj.run()  
  •    
  • //end of class  
  • OutputCompile Time Error

125
//final class final class Bike      class Honda1
 extends Bike     void run()System.out.println("
running safely with 100kmph")          public st
atic void main(String args)     Honda1 honda n
ew Honda()     honda.run()           OutputCo
mpile Time Error
126
final Keyword
  • final method is inherited but you cannot override
    it.
  • A final variable that is not initialized at the
    time of declaration is known as blank final
    variable.
  • We can initialize blank final variable only in
    constructor. For example
  • class Test  
  •    final int i//blank final variable  
  •     
  •    Test()  
  •    i80  
  •    ......  
  •     
  • If a method is declared private and final in
    superclass then we can have method with the same
    signature in subclass also because private is not
    inherited.
  • Constructor cannot be declared as final because
    constructor is never inherited.

127
  • static blank final variable
  • static final variable that is not initialized at
    the time of declaration .
  • Can be initialized only in static block.
  • Example
  • class Test  
  •   static final int data//static blank final varia
    ble  
  •   static data50  
  •   public static void main(String args)  
  •     System.out.println(Test.data)  
  •    
  •   

128
Polymorphism in Java Polymorphism in java is a
concept by which we can perform a single action
by different ways. Polymorphism is derived from 2
greek words poly and morphs. The word "poly"
means many and "morphs" means forms. So
polymorphism means many forms. There are two
types of polymorphism in java compile time
polymorphism and runtime polymorphism. We can
perform polymorphism in java by method
overloading and method overriding. If you
overload static method in java, it is the example
of compile time polymorphism. Here, we will focus
on runtime polymorphism in java. Runtime
Polymorphism in Java Runtime polymorphism or
Dynamic Method Dispatch is a process in which a
call to an overridden method is resolved at
runtime rather than compile-time. In this
process, an overridden method is called through
the reference variable of a superclass. The
determination of the method to be called is based
on the object being referred to by the reference
variable. Let's first understand the upcasting
before Runtime Polymorphism. Upcasting When
reference variable of Parent class refers to the
object of Child class, it is known as upcasting.
For example
129
  • class A  
  • class B extends A  
  • A anew B()//upcasting 
  •  
  • Real example of Java Runtime Polymorphism

130
  • class Bank  
  • int getRateOfInterest()return 0  
  •   
  •   
  • class SBI extends Bank  
  • int getRateOfInterest()return 8  
  •   
  •   
  • class ICICI extends Bank  
  • int getRateOfInterest()return 7  
  •   
  • class AXIS extends Bank  
  • int getRateOfInterest()return 9  
  •   
  •   
  • class Test3  
  • public static void main(String args)  
  • Bank b1new SBI()  
  • Bank b2new ICICI()  
  • Bank b3new AXIS()  
  • System.out.println("SBI Rate of Interest "b1.get
    RateOfInterest())  
  • System.out.println("ICICI Rate of Interest "b2.g
    etRateOfInterest())  
  • System.out.println("AXIS Rate of Interest "b3.ge
    tRateOfInterest())  
  •   
  •   

131
  • Java Runtime Polymorphism with data member
  • Method is overridden not the data members, so
    runtime polymorphism can't be achieved by data
    members.
  • class Bike
  • int speedlimit90
  • class Honda3 extends Bike
  • int speedlimit150
  • public static void main(String args)
  • Bike objnew Honda3()
  • System.out.println(obj.speedlimit)//90
  • Output90

132
  • Abstract class in Java
  • A class that is declared with abstract keyword,
    is known as abstract class in java. It can have
    abstract and non-abstract methods (method with
    body).
  • Abstraction in Java
  • Abstraction is a process of hiding the
    implementation details and showing only
    functionality to the user.
  • Another way, it shows only important things to
    the user and hides the internal details for
    example sending sms, you just type the text and
    send the message. You don't know the internal
    processing about the message delivery.
  • Abstraction lets you focus on what the object
    does instead of how it does it.
  • Ways to achieve Abstraction
  • Abstract class (0 to 100)
  • Interface (100)

133
  • Abstract class in Java
  • A class that is declared as abstract is known as
    abstract class. It needs to be extended and its
    method implemented. It cannot be instantiated.
  • Example abstract class
  • abstract class A
  • abstract method
  • A method that is declared as abstract and does
    not have implementation is known as abstract
    method.
  • Example abstract method
  • abstract void printStatus()//no body and
    abstract

134
  • Example of abstract class that has abstract
    method
  • In this example, Bike the abstract class that
    contains only one abstract method run. It
    implementation is provided by the Honda class.
  • abstract class Bike
  • abstract void run()
  • class Honda4 extends Bike
  • void run()System.out.println("running
    safely..")
  • public static void main(String args)
  • Bike obj new Honda4()
  • obj.run()
  • OUTPUT-running safely..

135
  • Understanding the real scenario of abstract class
  • In this example, Shape is the abstract class, its
    implementation is provided by the Rectangle and
    Circle classes. Mostly, we don't know about the
    implementation class (i.e. hidden to the end
    user) and object of the implementation class is
    provided by the factory method.
  • A factory method is the method that returns the
    instance of the class. We will learn about the
    factory method later.
  • In this example, if you create the instance of
    Rectangle class, draw() method of Rectangle class
    will be invoked.
  • abstract class Shape
  • abstract void draw()
  • class Rectangle extends Shape
  • void draw()System.out.println("drawing
    rectangle")
  • class Circle1 extends Shape
  • void draw()System.out.println("drawing
    circle")
  • //In real scenario, method is called by
    programmer or user
  • class TestAbstraction1
  • public static void main(String args)

136
  • An abstract class can have data member, abstract
    method, method body, constructor and even main()
    method.
  • Rule If there is any abstract method in a class,
    that class must be abstract.
  • If you are extending any abstract class that have
    abstract method, you must either provide the
    implementation of the method or make this class
    abstract.

137
  • Interface in Java
  • An interface in java is a blueprint of a class.
    It has static constants and abstract methods
    only.
  • The interface in java is a mechanism to achieve
    fully abstraction. There can be only abstract
    methods in the java interface not method body. It
    is used to achieve fully abstraction and multiple
    inheritance in Java.
  • Java Interface also represents IS-A relationship.
  • It cannot be instantiated just like abstract
    class.
  • The java compiler adds public and abstract
    keywords before the interface method and public,
    static and final keywords before data members.

138
(No Transcript)
139
Understanding relationship between classes
and interfaces
140
Simple example of Java interface In this
example, Printable interface have only one
method, its implementation is provided in the A
class. interface printable void print()
class A6 implements printable public void
print()System.out.println("Hello") public
static void main(String args) A6 obj new
A6() obj.print()
141
  • Multiple inheritance in Java by interface

142
  • interface Printable  
  • void print()  
  •   
  •   
  • interface Showable  
  • void show()  
  •   
  •   
  • class A7 implements Printable,Showable  
  •   
  • public void print()System.out.println("Hello") 
     
  • public void show()System.out.println("Welcome")
      
  •   
  • public static void main(String args)  
  • A7 obj  new A7()  
  • obj.print()  
  • obj.show()  
  •    
  •   

143
  • Multiple inheritance is not supported through
    class in java but it is possible by interface
  • interface Printable  
  • void print()  
  •   
  • interface Showable  
  • void print()  
  •   
  •   
  • class TestTnterface1 implements Printable,Showable
      
  • public void print()System.out.println("Hello") 
     
  • public static void main(String args)  
  • TestTnterface1 obj  new TestTnterface1()  
  • obj.print()  
  •    
  •   

144
  • Interface inheritance
  • A class implements interface but one interface
    extends another interface .
  • interface Printable  
  • void print()  
  •   
  • interface Showable extends Printable  
  • void show()  
  •   
  • class Testinterface2 implements Showable  
  •   
  • public void print()System.out.println("Hello") 
     
  • public void show()System.out.println("Welcome")
      
  •   
  • public static void main(String args)  
  • Testinterface2 obj  new Testinterface2()  
  • obj.print()  
  • obj.show()  
  •    

145
  • Marker or tagged interface?
  • An interface that have no member is known as
    marker or tagged interface. For example
    Serializable, Cloneable, Remote etc. They are
    used to provide some essential information to the
    JVM so that JVM may perform some useful
    operation.
  • //How Serializable interface is written?
  • public interface Serializable
  • Nested Interface in Java
  • Note An interface can have another interface
    i.e. known as nested interface. We will learn it
    in detail in the nested classes chapter. For
    example
  • interface printable
  • void print()
  • interface MessagePrintable
  • void msg()

146
Abstract class Interface
1) Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables.
) Abstract class can have static methods, main method and constructor. Interface can't have static methods, main method or constructor.
5) Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class.
6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
7) Examplepublic abstract class Shapepublic abstract void draw() Examplepublic interface Drawablevoid draw()
4
147
Core Java
148
  • Java Package
  • Group of similar types of classes, interfaces and
    sub-packages.
  • Types
  • built-in package (such as java, lang, io, util,
    sql etc.)
  • user-defined package.
  • Advantages
  • Used to categorize the classes and interfaces so
    that they can be easily maintained.
  • Provides access protection.
  • Removes naming collision.

149
Naming Conventions
Package names are written in all lower case to
avoid conflict with the names of classes or
interfaces. The prefix of a unique package name
is always written in all-lowercase ASCII letters
and should be one of the top-level domain names,
currently com, edu, gov, mil, net, org, or one of
the English two-letter codes identifying
countries as specified in ISO Standard 3166,
1981. Subsequent components of the package name
vary according to an organization's own internal
naming conventions. Such conventions might
specify that certain directory name components be
division, department, project, machine, or login
names.
150
(No Transcript)
151
  • Ways to access the package from outside the
    package
  • import packageName.
  • import packageName.classname
  • fully qualified name.
  • If you import a package, subpackages will not be
    imported.

152
Core Java
153
  • Access Modifiers
  • Specifies accessibility (scope) of a data member,
    method, constructor or class.
  • Types
  • private
  • package-private (no explicit modifier)
  • protected
  • public
  • There are many non-access modifiers such as
    static, abstract, synchronized, native, volatile,
    transient etc.

154
  •  private access modifier
  • Accessible only within class.
  • Role of Private Constructor
  • If you make any class constructor private, you
    cannot create the instance of that class from
    outside the class. For example
  • class A
  • private A()//private constructor
  • void msg()System.out.println("Hello java")
  • public class Simple
  • public static void main(String args)
  • A objnew A()//Compile Time Error
  • Note A class cannot be private or protected
    except nested class.

155
Access Modifier within class within package outside package by subclass only outside package
private Y N N N
package-private (no explicit modifier) Y Y N N
protected Y Y Y N
public Y Y Y Y
Note A class cannot be private or protected
except nested class.
156
The following table shows where the members of
the A class are visible for each of the access
modifiers that can be applied to them.
Visibiity
Modifier A B C D
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
157
  • Java Array
  • Collection of similar type of elements.
  • Contiguous memory location.
  • Fixed size.
  • Index based, first element of the array is stored
    at 0 index.

158
  • Types of Array
  • Single Dimensional Array
  • Multidimensional Array
  • Single Dimensional Array in java
  • Syntax
  • dataType  arr (or)  
  • dataType  arr (or)  
  • dataType  arr 
  •  
  • Instantiation
  • arrayRefVarnew datatypesize
  • Declaration, Instantiation and Initialization
  • int a33,3,4,5//declaration, instantiation an
    d initialization

159
Core Java
160
Diamond problem
  • An ambiguity that can arise as a consequence of
    allowing multiple inheritance.
  • Since Java 8 default methods have been permitted
    inside interfaces, which may cause ambiguity in
    some cases.

161
Diamond StructureCase1
interface A default void m()
System.out.println("m() from interface A ")
interface B extends A interface C
extends A public class D implements B,C
public static void main(String args)
new D().m()
162
Diamond StructureCase2
interface A default void m()
System.out.println("m() from interface A ")
interface B extends A _at_Override
default void m()
System.out.println("m() from interface B ")
interface C e
About PowerShow.com