SlideShare a Scribd company logo
Three Divisions for Access Modifiers
Outside Package Objects Accessing
Variables
 Private = Not Visible
 Protected = Not Visible
 Default = Not Visible
 Public = Visible
Functions
 Private =
 Protected
 Default =
 Public =

Not Visible
= Not Visible
Not Visible
Visible

Classes
 Default = Not visible
 Public = Visible

Inside Package Objects Accessing
Variables
 Private = Not Visible
 Protected = Visible
 Default = Visible
 Public = Visible
Functions
 Private = Not Visible
 Protected = Visible
 Default = Visible
 Public = Visible
Classes
 Default = Visible
 Public = Visible

Outside Package Subclass Objects Accessing = Main Difference
Variables
 Private = Not Visible
 Protected = Visible
 Default = Not Visible
 Public = Visible
Functions
 Private = Not Visible
 Protected = Visible
 Default = Not Visible
 Public = Visible
Classes
 Default = Not Visible
 Public = Visible
Variables and Methods Access Modifiers Summary

Variables and

Same Program

Objects within the

Sub Class Objects

Objects outside
Functions
Public
Protected
Default
Private

Objects
Visible
Visible
Visible
Visible

package
Visible
Visible
Visible
Not Visible

Outside package
Visible
Visible
Not Visible
Not Visible

package
Visible
Not Visible
Not Visible
Not Visible

Public

Same Program
Objects
Visible

Objects within
package
Visible

Sub Class Objects
outside package
Visible

Objects outside
Package
Visible

Default

Visible

Visible

Not Visible

Not Visible

Access Modifier Class Level
Classes

Final
Final Class = Cannot be extended within and outside the package
Final Function = Cannot be overridden in the sub class.
Final Variable = Value is like constant; New value cannot be assigned or modified anywhere.
Class Diagram for a Class Attributes and Methods of Washing Machine and ER Diagram

Java Access Modifiers for Class Level
1) Default = Accessed only within the package. (Meaning it can imported to create objects
out of it.)
2) Public = Accessed outside the package.
Other differences are = final and abstract; Final class level it cannot be sub classed but can be
instantiated. But abstract has to be sub classed and not instantiated.
Access Modifiers for Class Attributes
Public = Attribute can be accessed by class/objects in any package
Private = Attribute can be accessed from only within the class.
Protected = Attributes can be accessed from within the same package and the sub classes
outside the package
Default = Attributes can be accessed by same class or other classes/objects within the same
package.
Final = The value of the attribute cannot be changed. Only one value can be assigned
Static = Only one value of the attribute per class. Remains the same in all the objects
Access Modifiers = Method Level
Public = The method can be accessed by a class or object in any package
Private = Method can be accessed from only within the class
Protected = Method can be accessed by other classes or objects within the same package and the
class/objects sub-classing this methods‟ class outside the package
Default = Method can be accessed only be the other classes/objects within the same package and
the class/objects sub-classing this methods‟ class outside the package.
Final = Method cannot be overridden
Abstract = Only provides the method declaration not the definition.
Synchronized = Only one thread can access the method at a time
Constructors
 A constructor initializes an object upon creation.
 It has same name as that of the class in which it resides, Once defined the constructor is
automatically called immediately after the object creation.
 No return type
 Constructor‟s job is to initialize the inner state of an object so that the code creating the
instance of the class will have a fully initialized usable object immediately.
Two Types
 Default Constructor – When you do not explicitly define a constructor for a class, then
java creates a constructor for the class
 Parameterized Constructor – When the object is created, the user can send the values
to the constructor to initialize the attributes.
Example:public class Person {
int age;
short weight;
Person(int a, short w) {
age = a;
weight = w;
}}
When the object is created, it is like>> Person Sunil = new Person(23,63);
Static Methods
Static methods are class level methods which don‟t belong to one particular instance.
Instance method and Instance variable versus Static method and static variable;
In a static method there cannot be an instance variable; A static method is not allowed to
read or write the non-static methods of its class.
Polymorphism
Overloading Methods is Compile Time Polymorphism
 When we define two or more methods within the same class that share the same name but
their parameter declaration are different the methods are said to be overloaded and the
process is said to be method overloading.
 In own words suppose there are three methods anmely add(double a, double b) and add ()
And add (int a, int b). All three have same name but different parameters. When the
object of the class is defined and called as obj.add() obj.add(10.2,10.4) or obj (1,3) the
respective methods are called which have no parameters, double parameters and int
parameters respectively.
Overloading Constructors is also Polymorphism
 Constructors can also be overloaded;
Example:- public class Cube {
double width;
double height;
double length;
// Three overloaded constructors
Cube() { width = -1; height =-1; length = -1; }
Cube (double x) {width = x; height = x; length = x;}
Cube(double w,doubleh,double l) {width = w; height=h; length = l;}
public static void main (String args[]) {
// All three are valid
Cube c1 = new Cube();
Cube c2 = new Cube(3.2);
Cube c3= new Cuber (3.1, 2.4, 4.5);
}}
Copy Constructor
 Frequently we need to use the same values used in the different object to initialize the
current object. In that case we need to pass the object itself as the parameter.
public Cube {
double w; double h; double l;
Cube(double a,double b, double c) { w=a; h=b; l=c; }
Cube (Cube obj) { w = obj.w; h= obj.h; l= obj.l; }
public static void main (String args) {
Cube obj1 = new Cube(10,20,30);
Cube obj2 = new Cube(obj1);
}}
Inheritance
A class has data and methods. Inheritance is how a class can get data and methods
present in another class. Using extends keyword.
public class A {
inti,j;
voidshowij() {System.out.println(i+“ ”+ j);}
}

public class B extends A {
int k;
voidshowk() { System.out.println(k);}
void sum() { int sum = i+j+k; System.out,println(sum); }
}
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// Below can be done since B inherits the members and methods of A
B.i = 7; B.j = 8; B.k= 9;
B.sum();// Outputs 24 as result
}
}
Java does not support multiple Inheritance
Method Overriding
When the method with same name is present in the super class and same name and
signature is created and defined in the sub class. Then the method of the sub class
overrides the method of the super class. i.e. when the object of sub class calls this
method, the method of the sub class is called instead of the super class.
Class A {
int i, int j;
A(int a, int b) {i=a;j=b;}
void show() {System.out.println(i+” ”+j);}
}
Class B {
int k;
B (int a, int b, int c) { super(a,b); k =c; }
void show() {System.out.println(k);}
public static void main(String args[]) {
B subOb = new B (1,2,3);
subOb.show(); // Calls the subOb‟s show method which was overridden
}}
Super Keyword
 In own words. When the parent class has a parameterized constructor and the sub class
while defining a separate constructor, can use super keyword to initialize the inherited
constructors.
Run Time Polymorphism and Dynamic Dispatch
Call to an overridden method is resolved at run time
 In own words, suppose a class has members and method. The sub class inheriting from
the super class has the same method (overridden method). Now we define a super class
object and a sub class object. Now when we create a reference variable of super class and
then assign the object of the sub class, then at run time the compiler determines at run
time that the sub class method needs to be called.
Concept = Reference variable of a super class can be assigned the object of a sub class.
This causes run time polymorphism.
Example
class A { void callme() {System.out.println(“Inside A‟s callme method”);}}
class B extends A {
// Call me is overridden here
voidcallme() { System.out.println(“Inside B‟s callme method”);}}
class C extends A {
// Callme is overridden here too
voidcallme() {System.out.println(“Inside C‟s callme method”);
public static void main (String args[]) {
A a = new A(); // A‟s object
B b = new B(); // B‟s object
C c = new C(); // C‟s object
A r;
r = a;
r.show(); // A‟s method is called
r =b;
r.show(); // B‟s method is called // Run time polymorphism
r =c;
r.show(); // C „s method is called// Run time polymorphism
}}

Abstract Class and Abstract Method
 Many situations where a super class has only the generalized form and the sub classes
define the methods. Example Figure class containing parameters as l, b, h and area
function and triangle extending Figure class and defining the area.
 If we require a method be overridden by the sub classes, then we add abstract key word to
it.
 If more than one abstract method is present in a class then the class need to have keyword
called abstract
 An abstract class cannot be instantiated.
Example:
abstract class A {
// Abstract method
abstract void callme();
// properly defined method
voidcallmetoo() { System.out.println(“This is a concrete method.”);}
}
public class B extends A {
voidcallme() { System.out.println(“B‟s implementation of Callme”); }
public static void main(String args[]) {
B b = new B();
b.callme(); b.callmetoo(); // Both the methods work;
}}
Best example of abstract method is Figure class having two dimensions dim1 and dim2; There is
a parameterized constructor present which initializes the dimensions. The area method is kept as
abstract and not defined. Now Rectangle class extends this abstract Figure class and then calls
the super constructor for initialization and then defines its own area.Now the Triangle class does
the same thing except defining its own area.
Garbage Collection
 The problem is that the programs create objects which use a sizeable memory space and
other resources. Now when the objects are no longer in use they fill up the space and
create memory and other resource constraints.
 Garbage collector works this way. It remembers all the variables belonging to the
program and the objects which are pointed by these variables. These are called Reachable
objects. Unreachable objects are those that are not pointed by any of the current
programs.
 The garbage collector keeps track of the unreachable objects and deletes them and clears
the memory space.
 The GC acts in the background and cannot be controlled.
Package and Import
Package is like a directory. It contains group of classes and sub directories or sub packages.
It can be used to group classes with common purpose together and we can impart access
modifiers to the package so that the classes and objects outside the package cannot access classes
inside the package.
Import = If we need to use a public class present in another package we need to import the
contents of the package into the current class and then call the respective class for inheritance or
other purposes.
Interfaces
 Interface is a list of public method declarations.
 When the classes implement the interface, it is class‟s responsibility to implement all the
methods
 None of the methods in the interface are defined.
 A class is allowed to implement multiple interfaces.
 Interface has no state. It means that variables are treated as final static. The implementing
class need not have the same variables. If required, then switch to abstract class.
Example
public interface Figure {
public void area();
public void perimeter();
}
public class Rectangle implements Figure {
int l, int b;
public void area() { int area = l *b;}
public void perimeter() {intperi = 2*(l+b); }
}
public class Square implements Figure {
int s;
public void area () {int area = s * s;}
public void perimeter() {int perimeter = 4*s}
}
Exception Handling
Basic Concepts
Stack Trace
The JVM stores the functions in LIFO format as stack at run time. When the main method is
executed then main becomes bottom of stack and then any object called, the constructor takes the
position and then any other method called takes the position above the stack.
Now, when any method shows abnormal behavior, then error report is created known as stack
trace. This is useful for debugging of the code.
 Java exception Handling is managed via five key words = try catch finally throw
throws
 Exception handling means error handling. Error due to programmer or due to the system
happening at the run time.
 Exception Process = When the exception happens, an object representing that exception
is created and thrown in the method that caused the error. The method may catch it or
throw back. At some point exception is caught and then processed.
Example
class Exc0 { public static void main(String args[]) {
int d=0;
int a = 42/d; // We are attempting to divide by zero.
}}
When the program is run we get the following output: java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
 Reading the compiler message, it is a Arithmetic Exception; When this exception is
found by the compiler interrupting the normal behavior or flow of process, then object of
exception is created and at once handled by the Default Handler provided by Java Run
Time system which displays a string displaying the type of exception and the line of the
code where the exception had occurred.
Using try and Catch
Class Exc0 {
public static void main (String args[]) {
intd,a;
try { // Monitoring the block of code for Arithmetic Exception
d =0;
a = 42/d;
System.out.println(“This line is not printed.”);
}
catch (ArithmeticException e) {
System.out.println(“Division by Zero”);
}
}}
Multiple Catch Clauses
classMultiCatch {
public static void main (String args[]) {
try { // Manually monitoring the block for
int a = Integer.parseInt(args[0]);
int b = 42/a;
} catch (ArithmeticExceptionae ) {
System.out.println(“Divide by zero”);
} catch(ArrayOutOBoundsException e) {
System.out.println(“No Command line argument present.”);
} catch (NumberFormatException e) {
System.out.println(“Command Line argument is not a number.”); }
}}
JAVA Notes - All major concepts covered with examples

More Related Content

What's hot (20)

PPTX
Overloading and overriding in vb.net
suraj pandey
 
PPSX
Seminar on java
shathika
 
PPT
Java: Inheritance
Tareq Hasan
 
PPT
Java Programming - Inheritance
Oum Saokosal
 
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
PPTX
Class introduction in java
yugandhar vadlamudi
 
PPT
Lect 1-class and object
Fajar Baskoro
 
PPTX
Dynamic method dispatch
yugandhar vadlamudi
 
PPTX
Inheritance and Polymorphism Java
M. Raihan
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
PPS
Interface
kamal kotecha
 
PPTX
Pi j3.2 polymorphism
mcollison
 
PPTX
OOP C++
Ahmed Farag
 
PPT
Object Oriented Programming with Java
backdoor
 
PPTX
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
PPTX
Class and object
prabhat kumar
 
PPTX
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
DOC
Delphi qa
sandy14234
 
PPTX
Lecture 8 abstract class and interface
manish kumar
 
PPS
Inheritance chepter 7
kamal kotecha
 
Overloading and overriding in vb.net
suraj pandey
 
Seminar on java
shathika
 
Java: Inheritance
Tareq Hasan
 
Java Programming - Inheritance
Oum Saokosal
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute
 
Class introduction in java
yugandhar vadlamudi
 
Lect 1-class and object
Fajar Baskoro
 
Dynamic method dispatch
yugandhar vadlamudi
 
Inheritance and Polymorphism Java
M. Raihan
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
Interface
kamal kotecha
 
Pi j3.2 polymorphism
mcollison
 
OOP C++
Ahmed Farag
 
Object Oriented Programming with Java
backdoor
 
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
Class and object
prabhat kumar
 
Java Inheritance - sub class constructors - Method overriding
NithyaN19
 
Delphi qa
sandy14234
 
Lecture 8 abstract class and interface
manish kumar
 
Inheritance chepter 7
kamal kotecha
 

Similar to JAVA Notes - All major concepts covered with examples (20)

PPTX
Java presentation
Akteruzzaman .
 
PPTX
Chap3 inheritance
raksharao
 
PPTX
Object oriented concepts
Gousalya Ramachandran
 
DOC
116824015 java-j2 ee
homeworkping9
 
PDF
OOPs Concepts - Android Programming
Purvik Rana
 
PPT
Object and class
mohit tripathi
 
PDF
Java/J2EE interview Qestions
Arun Vasanth
 
PPT
Java inheritance
GaneshKumarKanthiah
 
PPTX
Polymorphism in java
Elizabeth alexander
 
PPTX
Inheritance.pptx
Karthik Rohan
 
PPTX
Introduction to OOPs second year cse.pptx
solemanhldr
 
PPTX
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
VGaneshKarthikeyan
 
PPTX
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
PPTX
Java session2
Rajeev Kumar
 
PPTX
introduction to object oriented programming language java
RitikGarg39
 
PPT
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
DOCX
Second chapter-java
Ahmad sohail Kakar
 
PPT
Inheritance and-polymorphism
Usama Malik
 
PPTX
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Java presentation
Akteruzzaman .
 
Chap3 inheritance
raksharao
 
Object oriented concepts
Gousalya Ramachandran
 
116824015 java-j2 ee
homeworkping9
 
OOPs Concepts - Android Programming
Purvik Rana
 
Object and class
mohit tripathi
 
Java/J2EE interview Qestions
Arun Vasanth
 
Java inheritance
GaneshKumarKanthiah
 
Polymorphism in java
Elizabeth alexander
 
Inheritance.pptx
Karthik Rohan
 
Introduction to OOPs second year cse.pptx
solemanhldr
 
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
VGaneshKarthikeyan
 
ITT 202 PRINCIPLES OF OBJECT ORIENTED TECHNIQUE
VinishA23
 
Java session2
Rajeev Kumar
 
introduction to object oriented programming language java
RitikGarg39
 
Chapter 5 (OOP Principles).ppt
henokmetaferia1
 
Second chapter-java
Ahmad sohail Kakar
 
Inheritance and-polymorphism
Usama Malik
 
702641313-CS3391-OBJORIENTEDPS-Unit-2.pptx
SAJITHABANUS
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Ad

More from Sunil Kumar Gunasekaran (20)

DOCX
CQL - Cassandra commands Notes
Sunil Kumar Gunasekaran
 
DOCX
Java J2EE Complete Syllabus Checklist
Sunil Kumar Gunasekaran
 
PDF
Amazon search test case document
Sunil Kumar Gunasekaran
 
DOC
Actual test case document
Sunil Kumar Gunasekaran
 
DOC
Sample Technical Requirement Document (TRD)
Sunil Kumar Gunasekaran
 
DOCX
Sql reference from w3 schools
Sunil Kumar Gunasekaran
 
DOCX
Sql commands worked out in sql plus with screen shots
Sunil Kumar Gunasekaran
 
DOCX
Wells fargo banking system ER Diagram
Sunil Kumar Gunasekaran
 
DOC
Business Requirements Document for Acounts Payable System
Sunil Kumar Gunasekaran
 
DOCX
Automation Testing Syllabus - Checklist
Sunil Kumar Gunasekaran
 
DOCX
Unix made easy
Sunil Kumar Gunasekaran
 
PDF
Test process - Important Concepts
Sunil Kumar Gunasekaran
 
DOCX
Testing http methods using Telnet
Sunil Kumar Gunasekaran
 
PDF
Test Life Cycle - Presentation - Important concepts covered
Sunil Kumar Gunasekaran
 
DOCX
Scrum writeup - Agile
Sunil Kumar Gunasekaran
 
DOCX
Scrum, V Model and RUP Models Overview
Sunil Kumar Gunasekaran
 
DOCX
PERL for QA - Important Commands and applications
Sunil Kumar Gunasekaran
 
DOCX
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Sunil Kumar Gunasekaran
 
DOCX
Fitnesse user acceptance test - Presentation
Sunil Kumar Gunasekaran
 
CQL - Cassandra commands Notes
Sunil Kumar Gunasekaran
 
Java J2EE Complete Syllabus Checklist
Sunil Kumar Gunasekaran
 
Amazon search test case document
Sunil Kumar Gunasekaran
 
Actual test case document
Sunil Kumar Gunasekaran
 
Sample Technical Requirement Document (TRD)
Sunil Kumar Gunasekaran
 
Sql reference from w3 schools
Sunil Kumar Gunasekaran
 
Sql commands worked out in sql plus with screen shots
Sunil Kumar Gunasekaran
 
Wells fargo banking system ER Diagram
Sunil Kumar Gunasekaran
 
Business Requirements Document for Acounts Payable System
Sunil Kumar Gunasekaran
 
Automation Testing Syllabus - Checklist
Sunil Kumar Gunasekaran
 
Unix made easy
Sunil Kumar Gunasekaran
 
Test process - Important Concepts
Sunil Kumar Gunasekaran
 
Testing http methods using Telnet
Sunil Kumar Gunasekaran
 
Test Life Cycle - Presentation - Important concepts covered
Sunil Kumar Gunasekaran
 
Scrum writeup - Agile
Sunil Kumar Gunasekaran
 
Scrum, V Model and RUP Models Overview
Sunil Kumar Gunasekaran
 
PERL for QA - Important Commands and applications
Sunil Kumar Gunasekaran
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Sunil Kumar Gunasekaran
 
Fitnesse user acceptance test - Presentation
Sunil Kumar Gunasekaran
 
Ad

Recently uploaded (20)

PDF
'' IMPORTANCE OF EXCLUSIVE BREAST FEEDING ''
SHAHEEN SHAIKH
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PPTX
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPTX
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPTX
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
'' IMPORTANCE OF EXCLUSIVE BREAST FEEDING ''
SHAHEEN SHAIKH
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
1, 2, 3… E MAIS UM CICLO CHEGA AO FIM!.pdf
Colégio Santa Teresinha
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
Federal dollars withheld by district, charter, grant recipient
Mebane Rash
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Pyhton with Mysql to perform CRUD operations.pptx
Ramakrishna Reddy Bijjam
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
community health nursing question paper 2.pdf
Prince kumar
 
How to Configure Lost Reasons in Odoo 18 CRM
Celine George
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 

JAVA Notes - All major concepts covered with examples

  • 1. Three Divisions for Access Modifiers Outside Package Objects Accessing Variables  Private = Not Visible  Protected = Not Visible  Default = Not Visible  Public = Visible Functions  Private =  Protected  Default =  Public = Not Visible = Not Visible Not Visible Visible Classes  Default = Not visible  Public = Visible Inside Package Objects Accessing Variables  Private = Not Visible  Protected = Visible  Default = Visible  Public = Visible Functions  Private = Not Visible  Protected = Visible  Default = Visible  Public = Visible Classes  Default = Visible  Public = Visible Outside Package Subclass Objects Accessing = Main Difference Variables  Private = Not Visible  Protected = Visible  Default = Not Visible  Public = Visible Functions  Private = Not Visible  Protected = Visible  Default = Not Visible  Public = Visible Classes  Default = Not Visible  Public = Visible Variables and Methods Access Modifiers Summary Variables and Same Program Objects within the Sub Class Objects Objects outside
  • 2. Functions Public Protected Default Private Objects Visible Visible Visible Visible package Visible Visible Visible Not Visible Outside package Visible Visible Not Visible Not Visible package Visible Not Visible Not Visible Not Visible Public Same Program Objects Visible Objects within package Visible Sub Class Objects outside package Visible Objects outside Package Visible Default Visible Visible Not Visible Not Visible Access Modifier Class Level Classes Final Final Class = Cannot be extended within and outside the package Final Function = Cannot be overridden in the sub class. Final Variable = Value is like constant; New value cannot be assigned or modified anywhere. Class Diagram for a Class Attributes and Methods of Washing Machine and ER Diagram Java Access Modifiers for Class Level 1) Default = Accessed only within the package. (Meaning it can imported to create objects out of it.) 2) Public = Accessed outside the package. Other differences are = final and abstract; Final class level it cannot be sub classed but can be instantiated. But abstract has to be sub classed and not instantiated.
  • 3. Access Modifiers for Class Attributes Public = Attribute can be accessed by class/objects in any package Private = Attribute can be accessed from only within the class. Protected = Attributes can be accessed from within the same package and the sub classes outside the package Default = Attributes can be accessed by same class or other classes/objects within the same package. Final = The value of the attribute cannot be changed. Only one value can be assigned Static = Only one value of the attribute per class. Remains the same in all the objects Access Modifiers = Method Level Public = The method can be accessed by a class or object in any package Private = Method can be accessed from only within the class Protected = Method can be accessed by other classes or objects within the same package and the class/objects sub-classing this methods‟ class outside the package Default = Method can be accessed only be the other classes/objects within the same package and the class/objects sub-classing this methods‟ class outside the package. Final = Method cannot be overridden Abstract = Only provides the method declaration not the definition. Synchronized = Only one thread can access the method at a time Constructors  A constructor initializes an object upon creation.  It has same name as that of the class in which it resides, Once defined the constructor is automatically called immediately after the object creation.  No return type  Constructor‟s job is to initialize the inner state of an object so that the code creating the instance of the class will have a fully initialized usable object immediately. Two Types  Default Constructor – When you do not explicitly define a constructor for a class, then java creates a constructor for the class  Parameterized Constructor – When the object is created, the user can send the values to the constructor to initialize the attributes. Example:public class Person { int age; short weight; Person(int a, short w) { age = a; weight = w; }} When the object is created, it is like>> Person Sunil = new Person(23,63); Static Methods
  • 4. Static methods are class level methods which don‟t belong to one particular instance. Instance method and Instance variable versus Static method and static variable; In a static method there cannot be an instance variable; A static method is not allowed to read or write the non-static methods of its class. Polymorphism Overloading Methods is Compile Time Polymorphism  When we define two or more methods within the same class that share the same name but their parameter declaration are different the methods are said to be overloaded and the process is said to be method overloading.  In own words suppose there are three methods anmely add(double a, double b) and add () And add (int a, int b). All three have same name but different parameters. When the object of the class is defined and called as obj.add() obj.add(10.2,10.4) or obj (1,3) the respective methods are called which have no parameters, double parameters and int parameters respectively. Overloading Constructors is also Polymorphism  Constructors can also be overloaded; Example:- public class Cube { double width; double height; double length; // Three overloaded constructors Cube() { width = -1; height =-1; length = -1; } Cube (double x) {width = x; height = x; length = x;} Cube(double w,doubleh,double l) {width = w; height=h; length = l;} public static void main (String args[]) { // All three are valid Cube c1 = new Cube(); Cube c2 = new Cube(3.2); Cube c3= new Cuber (3.1, 2.4, 4.5); }} Copy Constructor  Frequently we need to use the same values used in the different object to initialize the current object. In that case we need to pass the object itself as the parameter. public Cube { double w; double h; double l; Cube(double a,double b, double c) { w=a; h=b; l=c; } Cube (Cube obj) { w = obj.w; h= obj.h; l= obj.l; } public static void main (String args) { Cube obj1 = new Cube(10,20,30); Cube obj2 = new Cube(obj1); }}
  • 5. Inheritance A class has data and methods. Inheritance is how a class can get data and methods present in another class. Using extends keyword. public class A { inti,j; voidshowij() {System.out.println(i+“ ”+ j);} } public class B extends A { int k; voidshowk() { System.out.println(k);} void sum() { int sum = i+j+k; System.out,println(sum); } } public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // Below can be done since B inherits the members and methods of A B.i = 7; B.j = 8; B.k= 9; B.sum();// Outputs 24 as result } } Java does not support multiple Inheritance Method Overriding When the method with same name is present in the super class and same name and signature is created and defined in the sub class. Then the method of the sub class overrides the method of the super class. i.e. when the object of sub class calls this method, the method of the sub class is called instead of the super class. Class A { int i, int j; A(int a, int b) {i=a;j=b;} void show() {System.out.println(i+” ”+j);} } Class B { int k; B (int a, int b, int c) { super(a,b); k =c; } void show() {System.out.println(k);} public static void main(String args[]) { B subOb = new B (1,2,3); subOb.show(); // Calls the subOb‟s show method which was overridden }}
  • 6. Super Keyword  In own words. When the parent class has a parameterized constructor and the sub class while defining a separate constructor, can use super keyword to initialize the inherited constructors. Run Time Polymorphism and Dynamic Dispatch Call to an overridden method is resolved at run time  In own words, suppose a class has members and method. The sub class inheriting from the super class has the same method (overridden method). Now we define a super class object and a sub class object. Now when we create a reference variable of super class and then assign the object of the sub class, then at run time the compiler determines at run time that the sub class method needs to be called. Concept = Reference variable of a super class can be assigned the object of a sub class. This causes run time polymorphism. Example class A { void callme() {System.out.println(“Inside A‟s callme method”);}} class B extends A { // Call me is overridden here voidcallme() { System.out.println(“Inside B‟s callme method”);}} class C extends A { // Callme is overridden here too voidcallme() {System.out.println(“Inside C‟s callme method”); public static void main (String args[]) { A a = new A(); // A‟s object B b = new B(); // B‟s object C c = new C(); // C‟s object A r; r = a; r.show(); // A‟s method is called r =b; r.show(); // B‟s method is called // Run time polymorphism r =c; r.show(); // C „s method is called// Run time polymorphism }} Abstract Class and Abstract Method  Many situations where a super class has only the generalized form and the sub classes define the methods. Example Figure class containing parameters as l, b, h and area function and triangle extending Figure class and defining the area.  If we require a method be overridden by the sub classes, then we add abstract key word to it.
  • 7.  If more than one abstract method is present in a class then the class need to have keyword called abstract  An abstract class cannot be instantiated. Example: abstract class A { // Abstract method abstract void callme(); // properly defined method voidcallmetoo() { System.out.println(“This is a concrete method.”);} } public class B extends A { voidcallme() { System.out.println(“B‟s implementation of Callme”); } public static void main(String args[]) { B b = new B(); b.callme(); b.callmetoo(); // Both the methods work; }} Best example of abstract method is Figure class having two dimensions dim1 and dim2; There is a parameterized constructor present which initializes the dimensions. The area method is kept as abstract and not defined. Now Rectangle class extends this abstract Figure class and then calls the super constructor for initialization and then defines its own area.Now the Triangle class does the same thing except defining its own area. Garbage Collection  The problem is that the programs create objects which use a sizeable memory space and other resources. Now when the objects are no longer in use they fill up the space and create memory and other resource constraints.  Garbage collector works this way. It remembers all the variables belonging to the program and the objects which are pointed by these variables. These are called Reachable objects. Unreachable objects are those that are not pointed by any of the current programs.  The garbage collector keeps track of the unreachable objects and deletes them and clears the memory space.  The GC acts in the background and cannot be controlled. Package and Import Package is like a directory. It contains group of classes and sub directories or sub packages. It can be used to group classes with common purpose together and we can impart access modifiers to the package so that the classes and objects outside the package cannot access classes inside the package. Import = If we need to use a public class present in another package we need to import the contents of the package into the current class and then call the respective class for inheritance or other purposes. Interfaces  Interface is a list of public method declarations.
  • 8.  When the classes implement the interface, it is class‟s responsibility to implement all the methods  None of the methods in the interface are defined.  A class is allowed to implement multiple interfaces.  Interface has no state. It means that variables are treated as final static. The implementing class need not have the same variables. If required, then switch to abstract class. Example public interface Figure { public void area(); public void perimeter(); } public class Rectangle implements Figure { int l, int b; public void area() { int area = l *b;} public void perimeter() {intperi = 2*(l+b); } } public class Square implements Figure { int s; public void area () {int area = s * s;} public void perimeter() {int perimeter = 4*s} } Exception Handling Basic Concepts Stack Trace The JVM stores the functions in LIFO format as stack at run time. When the main method is executed then main becomes bottom of stack and then any object called, the constructor takes the position and then any other method called takes the position above the stack. Now, when any method shows abnormal behavior, then error report is created known as stack trace. This is useful for debugging of the code.  Java exception Handling is managed via five key words = try catch finally throw throws  Exception handling means error handling. Error due to programmer or due to the system happening at the run time.  Exception Process = When the exception happens, an object representing that exception is created and thrown in the method that caused the error. The method may catch it or throw back. At some point exception is caught and then processed. Example class Exc0 { public static void main(String args[]) { int d=0; int a = 42/d; // We are attempting to divide by zero. }} When the program is run we get the following output: java.lang.ArithmeticException: / by zero
  • 9. at Exc0.main(Exc0.java:4)  Reading the compiler message, it is a Arithmetic Exception; When this exception is found by the compiler interrupting the normal behavior or flow of process, then object of exception is created and at once handled by the Default Handler provided by Java Run Time system which displays a string displaying the type of exception and the line of the code where the exception had occurred. Using try and Catch Class Exc0 { public static void main (String args[]) { intd,a; try { // Monitoring the block of code for Arithmetic Exception d =0; a = 42/d; System.out.println(“This line is not printed.”); } catch (ArithmeticException e) { System.out.println(“Division by Zero”); } }} Multiple Catch Clauses classMultiCatch { public static void main (String args[]) { try { // Manually monitoring the block for int a = Integer.parseInt(args[0]); int b = 42/a; } catch (ArithmeticExceptionae ) { System.out.println(“Divide by zero”); } catch(ArrayOutOBoundsException e) { System.out.println(“No Command line argument present.”); } catch (NumberFormatException e) { System.out.println(“Command Line argument is not a number.”); } }}