SlideShare ist ein Scribd-Unternehmen logo
1 von 10
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

Weitere ähnliche Inhalte

Was ist angesagt?

Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.netsuraj pandey
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - InheritanceOum Saokosal
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and objectFajar Baskoro
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism JavaM. Raihan
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 

Was ist angesagt? (20)

Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
Interface
InterfaceInterface
Interface
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
OOP C++
OOP C++OOP C++
OOP C++
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
Class and object
Class and objectClass and object
Class and object
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 

Ähnlich wie JAVA Notes - All major concepts covered with examples

Ähnlich wie JAVA Notes - All major concepts covered with examples (20)

UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Inheritance
InheritanceInheritance
Inheritance
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
Oop inheritance chapter 3
Oop inheritance chapter 3Oop inheritance chapter 3
Oop inheritance chapter 3
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Chap11
Chap11Chap11
Chap11
 
Java02
Java02Java02
Java02
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Chapter 8.2
Chapter 8.2Chapter 8.2
Chapter 8.2
 
Core java oop
Core java oopCore java oop
Core java oop
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Only oop
Only oopOnly oop
Only oop
 

Mehr von Sunil Kumar Gunasekaran

Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)Sunil Kumar Gunasekaran
 
Sql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shotsSql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shotsSunil Kumar Gunasekaran
 
Business Requirements Document for Acounts Payable System
Business Requirements Document for Acounts Payable SystemBusiness Requirements Document for Acounts Payable System
Business Requirements Document for Acounts Payable SystemSunil Kumar Gunasekaran
 
Test Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts coveredTest Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts coveredSunil Kumar Gunasekaran
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsSunil Kumar Gunasekaran
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Sunil Kumar Gunasekaran
 
Fitnesse user acceptance test - Presentation
Fitnesse   user acceptance test - PresentationFitnesse   user acceptance test - Presentation
Fitnesse user acceptance test - PresentationSunil Kumar Gunasekaran
 

Mehr von Sunil Kumar Gunasekaran (20)

CQL - Cassandra commands Notes
CQL - Cassandra commands NotesCQL - Cassandra commands Notes
CQL - Cassandra commands Notes
 
Java J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus ChecklistJava J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus Checklist
 
Amazon search test case document
Amazon search test case documentAmazon search test case document
Amazon search test case document
 
Actual test case document
Actual test case documentActual test case document
Actual test case document
 
Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)Sample Technical Requirement Document (TRD)
Sample Technical Requirement Document (TRD)
 
Sql reference from w3 schools
Sql reference from w3 schools Sql reference from w3 schools
Sql reference from w3 schools
 
Sql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shotsSql commands worked out in sql plus with screen shots
Sql commands worked out in sql plus with screen shots
 
Wells fargo banking system ER Diagram
Wells fargo banking system ER DiagramWells fargo banking system ER Diagram
Wells fargo banking system ER Diagram
 
Business Requirements Document for Acounts Payable System
Business Requirements Document for Acounts Payable SystemBusiness Requirements Document for Acounts Payable System
Business Requirements Document for Acounts Payable System
 
Automation Testing Syllabus - Checklist
Automation Testing Syllabus - ChecklistAutomation Testing Syllabus - Checklist
Automation Testing Syllabus - Checklist
 
Unix short
Unix shortUnix short
Unix short
 
Unix made easy
Unix made easyUnix made easy
Unix made easy
 
Test process - Important Concepts
Test process - Important ConceptsTest process - Important Concepts
Test process - Important Concepts
 
Testing http methods using Telnet
Testing http methods using TelnetTesting http methods using Telnet
Testing http methods using Telnet
 
Test Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts coveredTest Life Cycle - Presentation - Important concepts covered
Test Life Cycle - Presentation - Important concepts covered
 
Scrum writeup - Agile
Scrum writeup - Agile Scrum writeup - Agile
Scrum writeup - Agile
 
Scrum, V Model and RUP Models Overview
Scrum, V Model and RUP Models OverviewScrum, V Model and RUP Models Overview
Scrum, V Model and RUP Models Overview
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
Java programs - bubble sort, iterator, linked list, hash set, reverse string,...
 
Fitnesse user acceptance test - Presentation
Fitnesse   user acceptance test - PresentationFitnesse   user acceptance test - Presentation
Fitnesse user acceptance test - Presentation
 

Kürzlich hochgeladen

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Kürzlich hochgeladen (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

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.”); } }}