SlideShare a Scribd company logo
1 of 122
checked exception
Core Java
mahika.a.motwani@gmail.com
Programming Languages
High Level Languages
(Machine independent)
Low-Level Languages
(Machine dependent)
Assembly
language
Machine(Binary)
language
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.
OOPs Concepts
Encapsulation
īƒ˜Binding (or wrapping) code and data together into a single unit.
īƒ˜A java class is the example of encapsulation.
Abstraction
īƒ˜Hiding internal details and showing functionality only.
With Abstraction
WithoutAbstraction
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.
Polymorphism
īƒ˜Ability to take multiple forms.
Example-
int a=10,b=20,c;
c=a+b; //addition
String firstname=“Sachin”, lastname=“Tendulkar”, fullname;
fullname=firstname+lastname;//concatenation
OOPLs
(Four OOPs features)
Partial OOPL Pure OOPLFully OOPL
īƒ˜Classes not mandatory.
īƒ˜Data members and methods can be
given outside class.
īƒ˜e.g. C++
īƒ˜Classes mandatory.
īƒ˜Data members and methods cannot
be given outside class.
īƒ˜e.g. Java
īƒ˜Classes mandatory.
īƒ˜Data members and methods cannot
be given outside class.
īƒ˜Primitive data types not supported.
īƒ˜e.g. Smalltalk
Java supports primitive data types , hence it is a fully OOPL but not pure OOPL.
int i=20; //primitive type
Integer a=new Integer(20); //Class type
Core Java
Signature of main()
public static void main(String[] args) {
â€Ļâ€Ļâ€Ļâ€Ļ..
â€Ļâ€Ļâ€Ļâ€Ļ..
}
returnType methodName(arguments)
{
â€Ļâ€Ļ
}
void m1()
{
â€Ļ..
â€Ļ..
}
int m2()
{
â€Ļ..
return 2;
}
int m3(int n)
{
â€Ļ..
return n*n;
}
public static void main(String[] args) {
â€Ļâ€Ļâ€Ļâ€Ļ..
â€Ļâ€Ļâ€Ļâ€Ļ..
}
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();
}
}
Invoking Member Funtions Of A Class
class Test
{
public static void main(String[] args)
{
-----
-----
-----
}
}
// Incase of static main()
Test.main();
Invoking 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.
// Incase of non-static main()
Test t=new Test()
t.main();
Thank You
Java Code (.java)
JAVAC
Compiler
Byte Code (.class)
JVM JVM JVM
Linux Mac Windows
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
JRE
īƒ˜ JRE is an acronym for Java Runtime Environment.
JRE
JVM
Llibraries
like rt.jar
Other files
JRE
JVM
Llibraries
like rt.jar
Other files
Development
tools like
javac, java etc.
JDK
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.
Internal Architecture of JVM
Java
Runtime
System
Class Loader
Class
Area
Heap Stack
PC
Register
Native
Method
Stack
Execution
engine
Native Method
Interface
Java Native
Libraries
Memory areas
allocated by JVM
Internal Architecture of JVM
Java
Runtime
System
Class Loader
Class
Area
Heap Stack
PC
Register
Native
Method
Stack
Execution
engine
Native Method
Interface
Java Native
Libraries
Memory areas
allocated by JVM
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.
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.
List of Java Keywords
Rules for Naming Java Identifiers
īƒ˜Allowed characters for identifiers are[A-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.
Java Identifiers
īƒ˜Names given to programming elements like variables, methods,
classes, packages and interfaces.
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.
Core Java
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.
Student
Data members
id
name
Methods
setId()
setName()
getId()
getName()
class
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;
}
}
Java class example
Instantiation/ Object Creation-
Classname referenceVariable=new Classname();
e.g.-
Student s=new Student();
Method Invocation/Call-
Non-static method:
referenceVariable.methodname();
e.g.- s.show();
static method:
Classname.methodname();
e.g.- Sample.display();
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.
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"));
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.
Thank You
Types of Variable
local instance static
public class Student
{
int rn; //instance variable
String name; //instance variable
static String college; //static variable
void m1()
{
int l; //local variable
â€Ļâ€Ļ
}
â€Ļâ€Ļâ€Ļ.
}
id=1
name= Hriday
Stack
Heap
id=2
name= Anil
s1
s2
college=“SVC””
Class Area
class Student{
int id;
String name;
static String college=“SVC”;
â€Ļâ€Ļâ€Ļ
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
â€Ļâ€Ļâ€Ļâ€Ļ
}
}
Thank You
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
Control Structures
1. Conditional
a) Simple if
b) if–else
c) if-else-if ladder
d) Nested if
e) switch case
2. Looping
a) while loop
b) for loop
c) do while loop
d) for each/enhanced for loop
if Statement:
if(condition){
//code to be executed
}
if –else Statement:
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
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
}
Test
Expression 1
Test
Expression 2
Test
Expression 3
No
No
No
Statement 1
Statement 2
Statement 3
else Body
Yes
Yes
Yes
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
}
Nested if
Core Java
switch Statement
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 matched;
}
Expression
case 1?
case 2?
case 3?
No
No
No
Case Block 1
Case Block 2
Case Block 3
default Block
Yes
Yes
Yes
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;
â€Ļâ€Ļâ€Ļâ€Ļ
}
īƒ˜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.
īƒ˜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.
while Loop
while(condition){
//code to be executed
}
do-while Loop
do{
//code to be executed
}while(condition);
for Loop
for(initialization;condition;incr/decr){
//code to be executed
}
break Statement
īƒ˜Used to break loop or switch statement.
continue Statement
īƒ˜Used to continue loop.
īƒ˜Skips the remaining code at specified condition.
Polymorphism
Run-time PolymorphismCompile-time Polymorphism
Method OverridingMethod Overloading
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:
1) By changing number of arguments
2) By changing the data type of arguments
Method Overloading is not possible by changing the return type or access specifier of a method.
Method Overloading and Type Promotion
īƒ˜ 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.
Ambiguity in Method Overloading
class Test{
void sum(int a,long b){System.out.println(a+b);}
void sum(long a,int b){System.out.println(a+b);}
public static void main(String args[]){
Test obj=new Test();
obj.sum(20,20);// ambiguity
}
}
Output:Compile Time Error
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
īƒ˜If there is no constructor in a class, compiler automatically creates a
default constructor.
class Student{
}
class Student{
Student()
{
}
}
compiler
Student.java Student.class
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
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
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).
//Program for static variable
class Student{
int id;
String name;
static String college =“SVC";
Student(int i,String n){
id=i;
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");
s1.display();
s2.display();
}
}
id=1
name= “Hriday”
Stack
Heap
id=2
name= “Anil”
s1
s2
college=“SVC””
Class Area
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.
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");
}
}
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() : 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
//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;
}
â€Ļâ€Ļâ€Ļ.
}
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.
class Test{
void m1( )
{ â€Ļ. }
void m2( )
{
m1()
}
â€Ļ.
}
class Test{
void m1( )
{ â€Ļ. }
void m2( )
{
this.m1()
}
â€Ļ.
}
compiler
Test.java Test.class
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);
}
public static void main(String[] args)
{
Test object = new Test();
object.get();
}
}
Output:-
a=40 b=60
Core Java
mahika.tutorials@gmail.com
this: to pass as argument in the constructor call
class B{
A obj;
B(A obj)
{
this.obj=obj;
}
void display(){
System.out.println(obj.data); //10
}
}
class A{
int data=10;
A()
{
B b=new B(this);
b.display();
}
public static void main(String args[]){
A a=new A();
}
}
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.
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
}
Types of inheritance in java
Multiple inheritance is not supported in java through 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
{
â€Ļâ€Ļ..
}
Object class
class A
{
â€Ļâ€Ļ.
}
class B extends A
{
â€Ļâ€Ļ.
}
class A extends Object
{
â€Ļâ€Ļ..
}
class B extends A
{
â€Ļâ€Ļ.
}
Object class
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.
Account
SavingAccount
Single Inheritance
Account
â€ĸ String accountId
â€ĸ double accountBalance
SavingAccount
â€ĸ double interestRate
â€ĸ double minimumBalance
Account
SavingAccount
SilverSavingAccount
Multilevel Inheritance
Account
â€ĸ String accountId
â€ĸ double acctBalance
SavingAccount
â€ĸ double interestRate
â€ĸ double minimumBalance
SilverSavingAcccount
â€ĸ String specialOfferId
Account
SavingAccount CurrentAccount
Hierarchical Inheritance
Account
â€ĸ String accountId
â€ĸ double acctBalance
SavingAccount
â€ĸ double interestRate
â€ĸ double minimumBalance
CurrentAccount
â€ĸ double transactionFee;
mahika.a.motwani@gmail.com
Multiple Inheritance
īƒ˜A feature where a class can inherit properties of more than one parent class.
īƒ˜Java doesn’t 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.
mahika.a.motwani@gmail.com
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 args[])
{
C obj=new C();
obj.show(); //ambiguity
}
}
mahika.a.motwani@gmail.com
Multiple Inheritance and Diamond Problem
mahika.a.motwani@gmail.com
Multiple inheritance in Java by interface
īƒ˜If a class implements multiple interfaces, or an interface extends multiple interfaces.
Polymorphism
Run-time PolymorphismCompile-time Polymorphism
Method OverridingMethod Overloading
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
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run(){System.out.println("Bike is running ”);}
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
Example:
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;
s=new Shape();
s.draw();
s =new Circle();
s.draw();
s=new Rectangle();
s.draw();
s=new Triangle();
s.draw();
}
}
At compile-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;
s=new Shape();
s.draw();
s =new Circle();
s.draw();
s=new Rectangle();
s.draw();
s=new Triangle();
s.draw();
}
}
At run-time:
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.
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(String args[])
{
Parent p=new Child();
p.msg();
}
}
class Parent{
void msg()
{
System.out.println("parent");
}
}
Output:Compile Time Error
īƒ˜ 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 p=new Child();
p.msg();
}
}
Output:child
īƒ˜ 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 p=new Child();
try{
p.msg();
}catch(Exception e){
}
}
}
class Parent{
void msg()throws ArithmeticException{
System.out.println("parent");
}
}
Output:Compile Time Error
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 p=new Child();
try{
p.msg();
}catch(Exception e){}
}
}
Example in case subclass overridden method declares subclass exception
Output:child
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
{
â€Ļâ€Ļâ€Ļ
}
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.
super used to refer immediate parent class instance variable:
class Vehicle{
int speed=70;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);// Vehicle speed
System.out.println(speed);// Bike speed
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}
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 b=new Bike();
}
}
īƒ˜ 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().
class Bike{
Bike()
{
}
}
class Bike{
Bike()
{
super();
}
}
compiler
Bike.java Bike .classa
super() :to invoke parent class constructor
super used to invoke parent class method:
class Vehicle{
void show(){System.out.println("Vehicle Runing");}
}
class Bike extends Vehicle{
void show(){System.out.println("Bike Runing ");
}
void display(){
super.show();
show();
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}
final Keyword
īƒ˜Used to restrict the user.
īƒ˜final can be:
1) Variableīƒ If you make any variable as final, you cannot change the
value of final variable(It will be constant).
2) Method->If you make any methode as final, you cannot override it.
3) Class->If you make any class as final, you cannot extend it.
īƒ˜ 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(){
i=80;
......
}
}
īƒ˜ 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.
final Keyword
Core Java
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.
Ways to access the package from outside the package:
1) import packageName.*;
2) import packageName.classname;
3) fully qualified name.
īƒ˜If you import a package, subpackages will not be imported.
Core Java
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.
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.
Mahika.a.motwani@gmail.com
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
Visibiity
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.
Package 1
A
B
Package 2
C
D
subclass
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.
Types of Array:
īƒ˜Single Dimensional Array
īƒ˜Multidimensional Array
Single Dimensional Array in java
Syntax:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation :
arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization :
int a[]={33,3,4,5};//declaration, instantiation and initialization
Core Java
Mahika.a.motwani@gmail.com
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.
Mahika.a.motwani@gmail.com
Diamond Structure:Case#1
[+] void m () <<default>>
<<interface>>
A
<<interface>>
B
<<interface>>
C
[+] void main(String arg[]) <<static>>
<<class>>
D
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();
}
}
Mahika.a.motwani@gmail.com
Diamond Structure:Case#2
[+] void m () <<default>>
<<interface>>
A
[+] void m () <<default>> <<override>>
<<interface>>
B
<<interface>>
C
[+] void main(String arg[]) <<static>>
<<class>>
D
interface A
{
default void m()
{
System.out.println("m() from interface A ");
}
}
interface B extends A
{
@Override
default void m()
{
System.out.println("m() from interface B ");
}
}
interface C extends A
{
}
public class D implements B,C {
public static void main(String[] args) {
new D().m();
}
}
Mahika.a.motwani@gmail.com
Diamond Structure:Case#3
[+] void m () <<default>>
<<interface>>
A
[+] void m () <<default>> <<override>>
<<interface>>
B
[+] void m () <<default>> <<override>>
<<interface>>
C
[+] void m () <<override>>
[+] void main(String arg[]) <<static>>
<<class>>
D
interface A
{
default void m()
{
System.out.println("m() from interface A ");
}
}
interface B extends A
{
@Override
default void m()
{
System.out.println("m() from interface B ");
}
}
interface C extends A
{
@Override
default void m()
{
System.out.println("m() from interface C");
}
}
public class D implements B,C {
@Override
public void m() {
B.super.m();
}
public static void main(String[] args) {
new D().m();
}
}

More Related Content

What's hot

Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 
Java architecture
Java architectureJava architecture
Java architectureRakesh Vadnala
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)Jadavsejal
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introductionjyoti_lakhani
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
Java Presentation
Java PresentationJava Presentation
Java Presentationpm2214
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSaba Ameer
 

What's hot (20)

Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
Java architecture
Java architectureJava architecture
Java architecture
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Core Java
Core JavaCore Java
Core Java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar to Learn core Java concepts like OOPs, classes, objects, inheritance and more

Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsAashish Jain
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx320126552027SURAKATT
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Nuzhat Memon
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction AKR Education
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slidesunny khan
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programmingNanthini Kempaiyan
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8 Bansilal Haudakari
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First LevelDr. Raaid Alubady
 
java intro.pptx.pdf
java intro.pptx.pdfjava intro.pptx.pdf
java intro.pptx.pdfTekobashiCarlo
 
Basics java programing
Basics java programingBasics java programing
Basics java programingDarshan Gohel
 
Java For Automation
Java   For AutomationJava   For Automation
Java For AutomationAbhijeet Dubey
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionGanesh Samarthyam
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docxNaorinHalim
 

Similar to Learn core Java concepts like OOPs, classes, objects, inheritance and more (20)

Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
Computational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptxComputational Problem Solving 016 (1).pptx
Computational Problem Solving 016 (1).pptx
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
 
Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction Unit 1 of java part 2 basic introduction
Unit 1 of java part 2 basic introduction
 
Java
Java Java
Java
 
Java OOP Concepts 1st Slide
Java OOP Concepts 1st SlideJava OOP Concepts 1st Slide
Java OOP Concepts 1st Slide
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 
Java Intro
Java IntroJava Intro
Java Intro
 
Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Functional Programming In Jdk8
Functional Programming In Jdk8 Functional Programming In Jdk8
Functional Programming In Jdk8
 
Hello java
Hello java   Hello java
Hello java
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First Level
 
Hello java
Hello java  Hello java
Hello java
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
 
java intro.pptx.pdf
java intro.pptx.pdfjava intro.pptx.pdf
java intro.pptx.pdf
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 

Recently uploaded

POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Recently uploaded (20)

Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Learn core Java concepts like OOPs, classes, objects, inheritance and more

  • 2. mahika.a.motwani@gmail.com Programming Languages High Level Languages (Machine independent) Low-Level Languages (Machine dependent) 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.
  • 5. Encapsulation īƒ˜Binding (or wrapping) code and data together into a single unit. īƒ˜A java class is the example of encapsulation.
  • 6. Abstraction īƒ˜Hiding internal details and showing functionality only. With Abstraction WithoutAbstraction
  • 7. 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.
  • 8. Polymorphism īƒ˜Ability to take multiple forms. Example- int a=10,b=20,c; c=a+b; //addition String firstname=“Sachin”, lastname=“Tendulkar”, fullname; fullname=firstname+lastname;//concatenation
  • 9. OOPLs (Four OOPs features) Partial OOPL Pure OOPLFully OOPL īƒ˜Classes not mandatory. īƒ˜Data members and methods can be given outside class. īƒ˜e.g. C++ īƒ˜Classes mandatory. īƒ˜Data members and methods cannot be given outside class. īƒ˜e.g. Java īƒ˜Classes mandatory. īƒ˜Data members and methods cannot be given outside class. īƒ˜Primitive data types not supported. īƒ˜e.g. Smalltalk Java supports primitive data types , hence it is a fully OOPL but not pure OOPL. int i=20; //primitive type Integer a=new Integer(20); //Class type
  • 12. public static void main(String[] args) { â€Ļâ€Ļâ€Ļâ€Ļ.. â€Ļâ€Ļâ€Ļâ€Ļ.. }
  • 13. returnType methodName(arguments) { â€Ļâ€Ļ } void m1() { â€Ļ.. â€Ļ.. } int m2() { â€Ļ.. return 2; } int m3(int n) { â€Ļ.. return n*n; }
  • 14. public static void main(String[] args) { â€Ļâ€Ļâ€Ļâ€Ļ.. â€Ļâ€Ļâ€Ļâ€Ļ.. }
  • 15. 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(); } } Invoking Member Funtions Of A Class
  • 16. class Test { public static void main(String[] args) { ----- ----- ----- } } // Incase of static main() Test.main(); Invoking 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. // Incase of non-static main() Test t=new Test() t.main();
  • 18. Java Code (.java) JAVAC Compiler Byte Code (.class) JVM JVM JVM Linux Mac Windows
  • 19. 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
  • 20. JRE īƒ˜ JRE is an acronym for Java Runtime Environment. JRE JVM Llibraries like rt.jar Other files
  • 21. JRE JVM Llibraries like rt.jar Other files Development tools like javac, java etc. JDK 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.
  • 22. Internal Architecture of JVM Java Runtime System Class Loader Class Area Heap Stack PC Register Native Method Stack Execution engine Native Method Interface Java Native Libraries Memory areas allocated by JVM
  • 23. Internal Architecture of JVM Java Runtime System Class Loader Class Area Heap Stack PC Register Native Method Stack Execution engine Native Method Interface Java Native Libraries Memory areas allocated by JVM
  • 24. 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.
  • 25. 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. List of Java Keywords
  • 26. Rules for Naming Java Identifiers īƒ˜Allowed characters for identifiers are[A-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. Java Identifiers īƒ˜Names given to programming elements like variables, methods, classes, packages and interfaces.
  • 27. 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.
  • 29. 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.
  • 31. 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; } } Java class example
  • 32. Instantiation/ Object Creation- Classname referenceVariable=new Classname(); e.g.- Student s=new Student(); Method Invocation/Call- Non-static method: referenceVariable.methodname(); e.g.- s.show(); static method: Classname.methodname(); e.g.- Sample.display();
  • 33. 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.
  • 34. 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"));
  • 35. 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.
  • 37. Types of Variable local instance static
  • 38. public class Student { int rn; //instance variable String name; //instance variable static String college; //static variable void m1() { int l; //local variable â€Ļâ€Ļ } â€Ļâ€Ļâ€Ļ. }
  • 39. id=1 name= Hriday Stack Heap id=2 name= Anil s1 s2 college=“SVC”” Class Area class Student{ int id; String name; static String college=“SVC”; â€Ļâ€Ļâ€Ļ public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); â€Ļâ€Ļâ€Ļâ€Ļ } }
  • 41.
  • 42. 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
  • 43. Control Structures 1. Conditional a) Simple if b) if–else c) if-else-if ladder d) Nested if e) switch case 2. Looping a) while loop b) for loop c) do while loop d) for each/enhanced for loop
  • 45. if –else Statement: if(condition){ //code if condition is true } else{ //code if condition is false }
  • 46. 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 } Test Expression 1 Test Expression 2 Test Expression 3 No No No Statement 1 Statement 2 Statement 3 else Body Yes Yes Yes
  • 47. if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } Nested if
  • 49. switch Statement 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 matched; } Expression case 1? case 2? case 3? No No No Case Block 1 Case Block 2 Case Block 3 default Block Yes Yes Yes
  • 50. 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; â€Ļâ€Ļâ€Ļâ€Ļ }
  • 51. īƒ˜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.
  • 52. īƒ˜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.
  • 54. do-while Loop do{ //code to be executed }while(condition);
  • 56. break Statement īƒ˜Used to break loop or switch statement.
  • 57. continue Statement īƒ˜Used to continue loop. īƒ˜Skips the remaining code at specified condition.
  • 59. 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: 1) By changing number of arguments 2) By changing the data type of arguments Method Overloading is not possible by changing the return type or access specifier of a method.
  • 60. Method Overloading and Type Promotion
  • 61. īƒ˜ 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.
  • 62. Ambiguity in Method Overloading class Test{ void sum(int a,long b){System.out.println(a+b);} void sum(long a,int b){System.out.println(a+b);} public static void main(String args[]){ Test obj=new Test(); obj.sum(20,20);// ambiguity } } Output:Compile Time Error
  • 63. 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
  • 64. īƒ˜If there is no constructor in a class, compiler automatically creates a default constructor. class Student{ } class Student{ Student() { } } compiler Student.java Student.class
  • 65. 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
  • 66. 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
  • 67. 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).
  • 68. //Program for static variable class Student{ int id; String name; static String college =“SVC"; Student(int i,String n){ id=i; 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"); s1.display(); s2.display(); } } id=1 name= “Hriday” Stack Heap id=2 name= “Anil” s1 s2 college=“SVC”” Class Area
  • 69. 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.
  • 70. 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"); } }
  • 71. 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.
  • 72. 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
  • 73. //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; } â€Ļâ€Ļâ€Ļ. }
  • 74. 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. class Test{ void m1( ) { â€Ļ. } void m2( ) { m1() } â€Ļ. } class Test{ void m1( ) { â€Ļ. } void m2( ) { this.m1() } â€Ļ. } compiler Test.java Test.class
  • 75. 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); } public static void main(String[] args) { Test object = new Test(); object.get(); } } Output:- a=40 b=60
  • 77. mahika.tutorials@gmail.com this: to pass as argument in the constructor call class B{ A obj; B(A obj) { this.obj=obj; } void display(){ System.out.println(obj.data); //10 } } class A{ int data=10; A() { B b=new B(this); b.display(); } public static void main(String args[]){ A a=new A(); } }
  • 78. 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.
  • 79. 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 }
  • 80. Types of inheritance in java Multiple inheritance is not supported in java through class
  • 81. īƒ˜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 { â€Ļâ€Ļ.. } Object class
  • 82. class A { â€Ļâ€Ļ. } class B extends A { â€Ļâ€Ļ. } class A extends Object { â€Ļâ€Ļ.. } class B extends A { â€Ļâ€Ļ. } Object class
  • 83. 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.
  • 84. Account SavingAccount Single Inheritance Account â€ĸ String accountId â€ĸ double accountBalance SavingAccount â€ĸ double interestRate â€ĸ double minimumBalance
  • 85. Account SavingAccount SilverSavingAccount Multilevel Inheritance Account â€ĸ String accountId â€ĸ double acctBalance SavingAccount â€ĸ double interestRate â€ĸ double minimumBalance SilverSavingAcccount â€ĸ String specialOfferId
  • 86. Account SavingAccount CurrentAccount Hierarchical Inheritance Account â€ĸ String accountId â€ĸ double acctBalance SavingAccount â€ĸ double interestRate â€ĸ double minimumBalance CurrentAccount â€ĸ double transactionFee;
  • 87. mahika.a.motwani@gmail.com Multiple Inheritance īƒ˜A feature where a class can inherit properties of more than one parent class. īƒ˜Java doesn’t 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.
  • 88. mahika.a.motwani@gmail.com 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 args[]) { C obj=new C(); obj.show(); //ambiguity } }
  • 90. mahika.a.motwani@gmail.com Multiple inheritance in Java by interface īƒ˜If a class implements multiple interfaces, or an interface extends multiple interfaces.
  • 92. 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 class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){System.out.println("Bike is running ”);} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } Example:
  • 93. 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; s=new Shape(); s.draw(); s =new Circle(); s.draw(); s=new Rectangle(); s.draw(); s=new Triangle(); s.draw(); } } At compile-time:
  • 94. 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; s=new Shape(); s.draw(); s =new Circle(); s.draw(); s=new Rectangle(); s.draw(); s=new Triangle(); s.draw(); } } At run-time:
  • 95. 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.
  • 96. 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(String args[]) { Parent p=new Child(); p.msg(); } } class Parent{ void msg() { System.out.println("parent"); } } Output:Compile Time Error
  • 97. īƒ˜ 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 p=new Child(); p.msg(); } } Output:child
  • 98. īƒ˜ 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 p=new Child(); try{ p.msg(); }catch(Exception e){ } } } class Parent{ void msg()throws ArithmeticException{ System.out.println("parent"); } } Output:Compile Time Error
  • 99. 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 p=new Child(); try{ p.msg(); }catch(Exception e){} } } Example in case subclass overridden method declares subclass exception Output:child
  • 100. 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 { â€Ļâ€Ļâ€Ļ }
  • 101. 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.
  • 102. super used to refer immediate parent class instance variable: class Vehicle{ int speed=70; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(super.speed);// Vehicle speed System.out.println(speed);// Bike speed } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }
  • 103. 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 b=new Bike(); } }
  • 104. īƒ˜ 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(). class Bike{ Bike() { } } class Bike{ Bike() { super(); } } compiler Bike.java Bike .classa super() :to invoke parent class constructor
  • 105. super used to invoke parent class method: class Vehicle{ void show(){System.out.println("Vehicle Runing");} } class Bike extends Vehicle{ void show(){System.out.println("Bike Runing "); } void display(){ super.show(); show(); } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }
  • 106. final Keyword īƒ˜Used to restrict the user. īƒ˜final can be: 1) Variableīƒ If you make any variable as final, you cannot change the value of final variable(It will be constant). 2) Method->If you make any methode as final, you cannot override it. 3) Class->If you make any class as final, you cannot extend it.
  • 107. īƒ˜ 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(){ i=80; ...... } } īƒ˜ 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. final Keyword
  • 109. 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.
  • 110.
  • 111. Ways to access the package from outside the package: 1) import packageName.*; 2) import packageName.classname; 3) fully qualified name. īƒ˜If you import a package, subpackages will not be imported.
  • 113. 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.
  • 114. 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.
  • 115. Mahika.a.motwani@gmail.com 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 Visibiity 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. Package 1 A B Package 2 C D subclass
  • 116. 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.
  • 117. Types of Array: īƒ˜Single Dimensional Array īƒ˜Multidimensional Array Single Dimensional Array in java Syntax: dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Instantiation : arrayRefVar=new datatype[size]; Declaration, Instantiation and Initialization : int a[]={33,3,4,5};//declaration, instantiation and initialization
  • 119. Mahika.a.motwani@gmail.com 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.
  • 120. Mahika.a.motwani@gmail.com Diamond Structure:Case#1 [+] void m () <<default>> <<interface>> A <<interface>> B <<interface>> C [+] void main(String arg[]) <<static>> <<class>> D 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(); } }
  • 121. Mahika.a.motwani@gmail.com Diamond Structure:Case#2 [+] void m () <<default>> <<interface>> A [+] void m () <<default>> <<override>> <<interface>> B <<interface>> C [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { @Override default void m() { System.out.println("m() from interface B "); } } interface C extends A { } public class D implements B,C { public static void main(String[] args) { new D().m(); } }
  • 122. Mahika.a.motwani@gmail.com Diamond Structure:Case#3 [+] void m () <<default>> <<interface>> A [+] void m () <<default>> <<override>> <<interface>> B [+] void m () <<default>> <<override>> <<interface>> C [+] void m () <<override>> [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { @Override default void m() { System.out.println("m() from interface B "); } } interface C extends A { @Override default void m() { System.out.println("m() from interface C"); } } public class D implements B,C { @Override public void m() { B.super.m(); } public static void main(String[] args) { new D().m(); } }