SlideShare uma empresa Scribd logo
1 de 56
Java Class 3
“Programming is magic which turn logic into reality”
•OOPS and its application in Java
•Super class AND This Keyword
•Java Bean, POJO
•Memory management in Java
•Packages
•Miscellaneous (Var-Args, toString(), Double
equals operator(==))
Java Basics 2
Agenda
OOPS and its application in Java
Super class AND This Keyword
Java Bean, POJO
Memory management in Java
Packages
Miscellaneous (Var-Args, toString(), Double
equals operator(==))
Java Basics 3
What are Classes and Objects?
Class is synonymous with data type
Object is like a variable
– The data type of the Object is some Class
– referred to as an instance of a Class
Classes contain:
– the implementation details of the data type
– and the interface for programmers who just want
to use the data type
Objects are complex variables
– usually multiple pieces of internal data
– various behaviors carried out via methods
Java Basics 4
Creating and Using Objects
Declaration - DataType identifier
Rectangle r1;
Creation - new operator and specified
constructor
r1 = new Rectangle();
Rectangle r2 = new Rectangle();
Behavior - via the dot operator
r2.setSize(10, 20);
String s2 = r2.toString();
Refer to documentation for available
behaviors (methods)
Java Basics 5
Built in Classes
Java has a large built
in library of classes
with lots of useful
methods
Ones you should
become familiar with
quickly
String
Math
Integer, Character,
Double
System
Arrays
Scanner
File
Object
Random
Look at the Java API
page
Java Basics 6
import
import is a reserved word
packages and classes can be imported to
another class
does not actually import the code (unlike the
C++ include preprocessor command)
statement outside the class block
import java.util.ArrayList;
import java.awt.Rectangle;
public class Foo{
// code for class Foo
}
Java Basics 7
More on import
can include a whole package
– import java.util.*;
or list a given class
– import java.util.Random;
instructs the compiler to look in the package for
types it can't find defined locally
the java.lang.* package is automatically
imported to all other classes.
Not required to import classes that are part of the
same project in Eclipse
Java Basics 8
The String Class
String is a standard Java class
– a whole host of behaviors via methods
also special (because it used so much)
– String literals exist (no other class has literals)
String name = "Mike D.";
– String concatenation through the + operator
String firstName = "Mike";
String lastName = "Scott";
String wholeName = firstName + lastName;
– Any primitive or object on other side of + operator
from a String automatically converted to String
Java Basics 9
Standard Output
To print to standard output use
System.out.print( expression ); // no newline
System.out.println( expression ); // newline
System.out.println( ); // just a newline
common idiom is to build up expression to
be printed out
System.out.println( "x is: " + x + " y is: " + y );
Java Basics 10
Methods
methods are analogous to procedures and
functions in other languages
– local variables, parameters, instance variables
– must be comfortable with variable scope: where is a
variable defined?
methods are the means by which objects are
manipulated (objects state is changed) - much
more on this later
method header consists of
– access modifier(public, package, protected, private)
– static keyword (optional, class method)
– return type (void or any data type, primitive or class)
– method name
– parameter signature
Java Basics 11
More on Methods
local variables can be declared within methods.
– Their scope is from the point of declaration until the
end of the methods, unless declared inside a
smaller block like a loop
methods contain statements
methods can call other methods
– in the same class: foo();
– methods to perform an operation on an object that
is in scope within the method: obj.foo();
– static methods in other classes:
double x = Math.sqrt(1000);
Java Basics 12
static methods
the main method is where a stand alone Java program
normally begins execution
common compile error, trying to call a non static method
from a static one
public class StaticExample
{ public static void main(String[] args)
{ //starting point of execution
System.out.println("In main method");
method1();
method2(); //compile error;
}
public static void method1()
{ System.out.println( "method 1"); }
public void method2()
{ System.out.println( "method 2"); }
}
Java Basics 13
Method Overloading and Return
a class may have multiple methods with the same
name as long as the parameter signature is unique
– may not overload on return type
methods in different classes may have same name
and signature
– this is a type of polymorphism, not method overloading
if a method has a return value other than void it
must have a return statement with a variable or
expression of the proper type
multiple return statements allowed, the first one
encountered is executed and method ends
– style considerations
Java Basics 14
Method Parameters
a method may have any number of
parameters
each parameter listed separately
no VAR (Pascal), &, or const & (C++)
final can be applied, but special meaning
all parameters are pass by value
Implications of pass by value???
Java Basics 15
Value Parameters vs.
Reference Parameters
A value parameter makes a copy of the
argument it is sent.
– Changes to parameter do not affect the
argument.
A reference parameter is just another name
for the argument it is sent.
– changes to the parameter are really changes to
the argument and thus are permanent
Java Basics 16
Value vs. Reference
// value
void add10(int x)
{ x += 10; }
void calls()
{ int y = 12;
add10(y);
// y = ?
}
// C++, reference
void add10(int& x)
{ x += 10; }
void calls()
{ int y = 12;
add10(y);
// y = ?
}
12
y
12
x
12
y x
Java Basics 17
Assertions
Assertions have the form
assert boolean expression : what to output
if assertion is false
Example
if ( (x < 0) || (y < 0) )
{ // we know either x or y is < 0
assert x < 0 || y < 0 : x + " " + y;
x += y;
}
else
{ // we know both x and y are not less than zero
assert x >= 0 && y >= 0 : x + " " + y;
y += x;
}
Use assertion liberally in your code
– part of style guide
Java Basics 18
Assertions Uncover Errors in
Your Logic
if ( a < b )
{ // we a is less than b
assert a < b : a + " " + b;
System.out.println(a + " is smaller than " + b);
}
else
{ // we know b is less than a
assert b < a : a + " " + b;
System.out.println(b + " is smaller than " + a);
}
Use assertions in code that other
programmers are going to use.
In the real world this is the majority of your
code!
OOPs
19
Appreciate OOPs concepts
Table of Content
20
Object oriented programming Class and Encapsulation
Object Reuse in Object Oriented Language
Attributes and Operations Inheritance
Class Inheritance hierarchy
Abstraction Generalization and Specialization
Encapsulation Polymorphism
Feature: Object oriented
programming
21
Terms
 Object
 Class
 Abstraction
 Encapsulation
 Inheritance
Object-oriented programming is a method of implementation in
which programs are organized as cooperative collections of
objects, each of which represents an instance of some class,
and whose classes are all members of a hierarchy of classes
united via inheritance relationships.
- Grady Booch
Object
22
A thing in a real world that can be either physical or
conceptual. An object in object oriented
programming can be physical or conceptual.
Conceptual objects are entities that are not
tangible in the way real-world physical objects are.
Bulb is a physical object. While college is a
conceptual object.
Conceptual objects may not have a real world
equivalent. For instance, a Stack object in a
program.
Object has state and behavior.What is the state and behavior of this bulb?
Attributes and Operations
23
The object’s state is determined by the value
of its properties or attributes.
Properties or attributes  member variables
or data members
The object’s behaviour is determined by the
operations that it provides.
Operations  member functions or methods
A bulb:
1. It’s a real-world thing.
2. Can be switched on to generate light and switched off.
3. It has real features like the glass covering, filament and holder.
4. It also has conceptual features like power.
5. A bulb manufacturing factory produces many bulbs based on a basic
description / pattern of what a bulb is.
object
methods
member variables
class
Putting it together
24
Class
25
A class is a construct created in object-
oriented programming languages that
enables creation of objects.
Also sometimes called blueprint or template
or prototype from which objects are created.
It defines members (variables and methods).
A class is an abstraction.
Abstraction
Abstraction is the process of taking only a
set of essential characteristics from
something.
Example
– For a Doctor you are a Patient
• Name, Age, Old medical records
– For a Teacher you are a Student
• Name, Roll Number/RegNo, Education background
– For HR Staff you are ______________
• ___________,_____________,___________
Yo
u
Abstraction denotes essential characteristics of an object that
distinguish it from all other kinds of objects and thus provide crisply
defined conceptual boundaries, relative to the perspective of the
viewer.
-Grady Booch
Encapsulation
27
Encapsulation is binding data and operations
that work on data together in a construct.
Encapsulation involves Data and
Implementation Hiding.
Would you like it if your CPU is given
to you like this?
What are the problems if it were given
to you like this?
Encapsulation is the process of compartmentalizing the elements of
abstraction that constitute its structure and behavior; encapsulation
serves to separate the contractual interface of an abstraction and its
implementation.
- Grady Booch
Class and Encapsulation
28
Student
• -roll: long
• -name: String
• + display(): void
• + read(): boolean
Rectangle
• -length: int
• -width:int
• +area(): int
LinkedList
• -Node
• + addFirst(Node n)
• + remove(Node n)
• + add(Node n, int pos)
- : private
+ : public
Reuse in Object Oriented
Language
29
Object Oriented Languages also implements reuse
in the same way that we do in real life.
Using
– has-a
– is-a
Has-a or composition relationship is implemented
by having a class having another class as its
member, or rather an object having another object
as its member.
– Car has a Stereo
– College has Teachers and Students
Is-a is implemented through what we call
inheritance relationship
Inheritance
30
Defines IS-A relationship between classes
Cat IS-A Animal
Car IS-A Vehicle
Rose IS-A Flower
Inheritance defines relationship among classes, wherein one class
share structure or behavior defined in one or more classes.
- Grady Booch
Inheritance hierarchy
Animal
legs
tail
run()
Dog
bark() Tiger
growl()
CatFamily
paddedClaws
whiskers
Cat
meow()
Single -level
Multi-level
32
Many Object-orientated language does
not support this type of inheritance.
Java, C# are the examples of object-
oriented language that does not support
multiple inheritance through classes.
Mammal Bird
Bat
Multiple inheritance
Generalization and
Specialization
WildAnimal
legs
tail
run()
Tiger
growl()
CatFamily
paddedClaws
whiskers
Cat
meow()
Speciali
zation
Generaliz
ation
Activity: match the following
Super class Subclass
34
 Fruit
 Library
 Cat
 Bird
 Parrot
 Music
 Tiger
 Books
 Apple
 Mango
Activity
35
Given the following classes. Can you form
inheritance hierarchy?
– Person
– Teacher
– Student
– HOD
– Typist
– Clerk
What are the common members shared ?
Polymorphism
36
A concept in type theory, according to which a name (such
as a
variable declaration) may denote objects of many different
classes that are related by some common superclass; thus,
any object denoted by this name is able to respond to some
common set of operations in different ways.
- Grady Booch
Polymorphism example
37
Flower
fragrance()
Rose
fragrance()
Sunflower
fragrance()
FlowerVase
Flower f[]
38
You pick a rose from the vase and
smell it?
What fragrance do you expect?
Flower
fragrance()
Rose
fragrance()
Sunflower
fragrance()
FlowerVase
Flower f[]
smell()
f[0]= rose;
f[1]=
sunflower;
….
f[0].
fragrance();
f[1].
fragrance();
…
Exercise: Inheritance
39
Among the classes that you identified, are
there any classes that you can relate via
inheritance.
(Hint: are there any classes which have
common attributes/methods that can be moved
up the hierarchy)
Revisiting definition
40
Object-oriented programming is a method of
implementation in which programs are organized as
cooperative collections of objects, each of which
represents an instance of some class, and whose
classes are all members of a hierarchy of classes
united via inheritance relationships.
Rama
123
Student
• -roll: long
• + read(): boolean
B.Tech
2010
Course
• -name: String
• -year: Date
• + display(): void
• + enroll(Student): boolean
enroll()
Person
• -name: String
• + display(): void
Summary
41
Object-oriented programming is a method of
implementation in which programs are organized as
cooperative collections of objects.
The object’s state is determined by the value of its
properties and its behavior is determined by the
operations that it provides.
Abstraction is the process of taking only a set of
essential characteristics from something.
Encapsulation is binding data and operations that work
on data together in a construct.
Inheritance defines relationship among classes, wherein
one class share structure or behavior defined in one or
more classes.
Polymorphism is using a function in many forms. Poly
means ‘many’, Morphism means ‘forms’.
Super keyword in java
Super keyword is a reference variable that is
used for refer parent class object.
Super Keyword is mainly used at three
level in java
At variable level
At method level
At constructor level
Java Basics 42
Why use super keyword in
java?
Whenever inherit base class data into
derived class it is chance to get ambiguity,
because may be base class and derived
class data are same so to difference these
data need to use super keyword
Java Basics 43
Example of Super Keyword
class Employee {
float salary=10000;
}
class HR extends Employee {
float salary=20000;
void display() {
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class Supervarible {
public static void main(String[] args) {
HR obj=new HR();
obj.display();
}
}
Java Basics 44
This keyword in java
This keyword is a reference variable that
refers the current object in java.
This keyword can be used for call current
class constructor.
The main uses of this keyword is to
differentiate the formal parameter and data
members of class.
o this.show() // method
o this.s = s // variable
Java Basics 45
Memory Management
Java Basics 46
PROCEDURE
• After reading .class file, class loader save the corresponding byte
code in the method area. Generally all JVMs have only one method
area which is shared across classes which holds information related
to each .class file.
• Heap is an integral part of JVM memory in which the objects
actually rests. JVM produces the Class object for each .class file.
• Unlike Heap, Stack is used for storing temporary variables.
• PC-Registers used to keep exact information of all instructions
(which instruction is executing and which is going to be executed).
• A native method used to access the runtime data of the JVM (java
virtual machine). Native Method interface enables java code to call
by the native applications (programs that are specific to the
hardware and OS).
Java Basics 47
JRE ( Java Runtime Environment )
• Java Runtime Environment is within which
the java virtual machine actually runs. JRE
contains Java virtual Machine and other files
except development tools (debugger and
compiler). So developer can run the source
code in JRE but he/she cannot develop and
compile the code.
Java Basics 48
JVM ( Java Virtual Machine )
• JVM runs the program by using libraries and files
provided by Java Runtime Environment.
JDK ( Java Development Kit )
• Java Development Kit can be considered as the
super-set of JRE. JDK includes all features that
JRE has and over and above it contains
development tools such like compiler, debugger
etc.
Java Basics 49
Memory Management
 Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant
pool, field and method data, the code for methods.
 Heap
It is the runtime data area in which objects are allocated.
 Stack
Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.
 Class Loader
Bootstrap ClassLoader , Extension ClassLoader, System/Application ClassLoader:
Java Basics 50
 Program Counter Register
PC (program counter) register contains the address of the Java virtual
machine instruction currently being executed.
 Native Method Stack
It contains all the native methods used in the application.
 Execution Engine
It contains:
1. A virtual processor Interpreter
2. Just-In-Time(JIT) compiler
 Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to
communicate with another application written in another language like C,
C++, Assembly etc. Java uses JNI framework to send output to the Console
or interact with OS libraries.
Java Basics 51
Packages
Need for packages
What are packages; package declaration in
Java
Import statement in Java
How do packages resolve name clashes?
Ex . Package com.main.view
package com.main.model
package com.main.dto
Java Basics 52
Miscellenous
Double equals operator(==): comaprision
toString():to convert the value in string value.
Reference variables, local variables,
instance variables
A variable declared inside the body of the method
is called local variable. You can use this variable
only within that method and the other methods in
the class aren't even aware that the variable exists.
A local variable cannot be defined with "static"
keyword.
Java Basics 53
2) Instance Variable
A variable declared inside the class but outside the body of the
method, is called instance variable. It is not declared
as static.
It is called instance variable because its value is instance
specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It
cannot be local. You can create a single copy of static
variable and share among all the instances of the class.
Memory allocation for static variable happens only once
when the class is loaded in the memory.
Java Basics 54
Example
class A{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class
Java Basics 55
Q & A
???
Java Basics 56
For Engineering project please
visit mindlabz software

Mais conteúdo relacionado

Mais procurados

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 

Mais procurados (17)

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Java
Java Java
Java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 

Semelhante a OOPS in java | Super and this Keyword | Memory Management in java | pacakages | tostring in java

Semelhante a OOPS in java | Super and this Keyword | Memory Management in java | pacakages | tostring in java (20)

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
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Lecture 2 classes i
Lecture 2 classes iLecture 2 classes i
Lecture 2 classes i
 
Java basics
Java basicsJava basics
Java basics
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 

Mais de Sagar Verma

Mais de Sagar Verma (7)

Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Java introduction
Java introductionJava introduction
Java introduction
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introduction
 
2015-16 software project list
2015-16 software project list2015-16 software project list
2015-16 software project list
 
Ns2 new project list
Ns2 new project listNs2 new project list
Ns2 new project list
 
Privacy preserving dm_ppt
Privacy preserving dm_pptPrivacy preserving dm_ppt
Privacy preserving dm_ppt
 

Último

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 

OOPS in java | Super and this Keyword | Memory Management in java | pacakages | tostring in java

  • 1. Java Class 3 “Programming is magic which turn logic into reality” •OOPS and its application in Java •Super class AND This Keyword •Java Bean, POJO •Memory management in Java •Packages •Miscellaneous (Var-Args, toString(), Double equals operator(==))
  • 2. Java Basics 2 Agenda OOPS and its application in Java Super class AND This Keyword Java Bean, POJO Memory management in Java Packages Miscellaneous (Var-Args, toString(), Double equals operator(==))
  • 3. Java Basics 3 What are Classes and Objects? Class is synonymous with data type Object is like a variable – The data type of the Object is some Class – referred to as an instance of a Class Classes contain: – the implementation details of the data type – and the interface for programmers who just want to use the data type Objects are complex variables – usually multiple pieces of internal data – various behaviors carried out via methods
  • 4. Java Basics 4 Creating and Using Objects Declaration - DataType identifier Rectangle r1; Creation - new operator and specified constructor r1 = new Rectangle(); Rectangle r2 = new Rectangle(); Behavior - via the dot operator r2.setSize(10, 20); String s2 = r2.toString(); Refer to documentation for available behaviors (methods)
  • 5. Java Basics 5 Built in Classes Java has a large built in library of classes with lots of useful methods Ones you should become familiar with quickly String Math Integer, Character, Double System Arrays Scanner File Object Random Look at the Java API page
  • 6. Java Basics 6 import import is a reserved word packages and classes can be imported to another class does not actually import the code (unlike the C++ include preprocessor command) statement outside the class block import java.util.ArrayList; import java.awt.Rectangle; public class Foo{ // code for class Foo }
  • 7. Java Basics 7 More on import can include a whole package – import java.util.*; or list a given class – import java.util.Random; instructs the compiler to look in the package for types it can't find defined locally the java.lang.* package is automatically imported to all other classes. Not required to import classes that are part of the same project in Eclipse
  • 8. Java Basics 8 The String Class String is a standard Java class – a whole host of behaviors via methods also special (because it used so much) – String literals exist (no other class has literals) String name = "Mike D."; – String concatenation through the + operator String firstName = "Mike"; String lastName = "Scott"; String wholeName = firstName + lastName; – Any primitive or object on other side of + operator from a String automatically converted to String
  • 9. Java Basics 9 Standard Output To print to standard output use System.out.print( expression ); // no newline System.out.println( expression ); // newline System.out.println( ); // just a newline common idiom is to build up expression to be printed out System.out.println( "x is: " + x + " y is: " + y );
  • 10. Java Basics 10 Methods methods are analogous to procedures and functions in other languages – local variables, parameters, instance variables – must be comfortable with variable scope: where is a variable defined? methods are the means by which objects are manipulated (objects state is changed) - much more on this later method header consists of – access modifier(public, package, protected, private) – static keyword (optional, class method) – return type (void or any data type, primitive or class) – method name – parameter signature
  • 11. Java Basics 11 More on Methods local variables can be declared within methods. – Their scope is from the point of declaration until the end of the methods, unless declared inside a smaller block like a loop methods contain statements methods can call other methods – in the same class: foo(); – methods to perform an operation on an object that is in scope within the method: obj.foo(); – static methods in other classes: double x = Math.sqrt(1000);
  • 12. Java Basics 12 static methods the main method is where a stand alone Java program normally begins execution common compile error, trying to call a non static method from a static one public class StaticExample { public static void main(String[] args) { //starting point of execution System.out.println("In main method"); method1(); method2(); //compile error; } public static void method1() { System.out.println( "method 1"); } public void method2() { System.out.println( "method 2"); } }
  • 13. Java Basics 13 Method Overloading and Return a class may have multiple methods with the same name as long as the parameter signature is unique – may not overload on return type methods in different classes may have same name and signature – this is a type of polymorphism, not method overloading if a method has a return value other than void it must have a return statement with a variable or expression of the proper type multiple return statements allowed, the first one encountered is executed and method ends – style considerations
  • 14. Java Basics 14 Method Parameters a method may have any number of parameters each parameter listed separately no VAR (Pascal), &, or const & (C++) final can be applied, but special meaning all parameters are pass by value Implications of pass by value???
  • 15. Java Basics 15 Value Parameters vs. Reference Parameters A value parameter makes a copy of the argument it is sent. – Changes to parameter do not affect the argument. A reference parameter is just another name for the argument it is sent. – changes to the parameter are really changes to the argument and thus are permanent
  • 16. Java Basics 16 Value vs. Reference // value void add10(int x) { x += 10; } void calls() { int y = 12; add10(y); // y = ? } // C++, reference void add10(int& x) { x += 10; } void calls() { int y = 12; add10(y); // y = ? } 12 y 12 x 12 y x
  • 17. Java Basics 17 Assertions Assertions have the form assert boolean expression : what to output if assertion is false Example if ( (x < 0) || (y < 0) ) { // we know either x or y is < 0 assert x < 0 || y < 0 : x + " " + y; x += y; } else { // we know both x and y are not less than zero assert x >= 0 && y >= 0 : x + " " + y; y += x; } Use assertion liberally in your code – part of style guide
  • 18. Java Basics 18 Assertions Uncover Errors in Your Logic if ( a < b ) { // we a is less than b assert a < b : a + " " + b; System.out.println(a + " is smaller than " + b); } else { // we know b is less than a assert b < a : a + " " + b; System.out.println(b + " is smaller than " + a); } Use assertions in code that other programmers are going to use. In the real world this is the majority of your code!
  • 20. Table of Content 20 Object oriented programming Class and Encapsulation Object Reuse in Object Oriented Language Attributes and Operations Inheritance Class Inheritance hierarchy Abstraction Generalization and Specialization Encapsulation Polymorphism
  • 21. Feature: Object oriented programming 21 Terms  Object  Class  Abstraction  Encapsulation  Inheritance Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships. - Grady Booch
  • 22. Object 22 A thing in a real world that can be either physical or conceptual. An object in object oriented programming can be physical or conceptual. Conceptual objects are entities that are not tangible in the way real-world physical objects are. Bulb is a physical object. While college is a conceptual object. Conceptual objects may not have a real world equivalent. For instance, a Stack object in a program. Object has state and behavior.What is the state and behavior of this bulb?
  • 23. Attributes and Operations 23 The object’s state is determined by the value of its properties or attributes. Properties or attributes  member variables or data members The object’s behaviour is determined by the operations that it provides. Operations  member functions or methods
  • 24. A bulb: 1. It’s a real-world thing. 2. Can be switched on to generate light and switched off. 3. It has real features like the glass covering, filament and holder. 4. It also has conceptual features like power. 5. A bulb manufacturing factory produces many bulbs based on a basic description / pattern of what a bulb is. object methods member variables class Putting it together 24
  • 25. Class 25 A class is a construct created in object- oriented programming languages that enables creation of objects. Also sometimes called blueprint or template or prototype from which objects are created. It defines members (variables and methods). A class is an abstraction.
  • 26. Abstraction Abstraction is the process of taking only a set of essential characteristics from something. Example – For a Doctor you are a Patient • Name, Age, Old medical records – For a Teacher you are a Student • Name, Roll Number/RegNo, Education background – For HR Staff you are ______________ • ___________,_____________,___________ Yo u Abstraction denotes essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer. -Grady Booch
  • 27. Encapsulation 27 Encapsulation is binding data and operations that work on data together in a construct. Encapsulation involves Data and Implementation Hiding. Would you like it if your CPU is given to you like this? What are the problems if it were given to you like this? Encapsulation is the process of compartmentalizing the elements of abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation. - Grady Booch
  • 28. Class and Encapsulation 28 Student • -roll: long • -name: String • + display(): void • + read(): boolean Rectangle • -length: int • -width:int • +area(): int LinkedList • -Node • + addFirst(Node n) • + remove(Node n) • + add(Node n, int pos) - : private + : public
  • 29. Reuse in Object Oriented Language 29 Object Oriented Languages also implements reuse in the same way that we do in real life. Using – has-a – is-a Has-a or composition relationship is implemented by having a class having another class as its member, or rather an object having another object as its member. – Car has a Stereo – College has Teachers and Students Is-a is implemented through what we call inheritance relationship
  • 30. Inheritance 30 Defines IS-A relationship between classes Cat IS-A Animal Car IS-A Vehicle Rose IS-A Flower Inheritance defines relationship among classes, wherein one class share structure or behavior defined in one or more classes. - Grady Booch
  • 32. 32 Many Object-orientated language does not support this type of inheritance. Java, C# are the examples of object- oriented language that does not support multiple inheritance through classes. Mammal Bird Bat Multiple inheritance
  • 34. Activity: match the following Super class Subclass 34  Fruit  Library  Cat  Bird  Parrot  Music  Tiger  Books  Apple  Mango
  • 35. Activity 35 Given the following classes. Can you form inheritance hierarchy? – Person – Teacher – Student – HOD – Typist – Clerk What are the common members shared ?
  • 36. Polymorphism 36 A concept in type theory, according to which a name (such as a variable declaration) may denote objects of many different classes that are related by some common superclass; thus, any object denoted by this name is able to respond to some common set of operations in different ways. - Grady Booch
  • 38. 38 You pick a rose from the vase and smell it? What fragrance do you expect? Flower fragrance() Rose fragrance() Sunflower fragrance() FlowerVase Flower f[] smell() f[0]= rose; f[1]= sunflower; …. f[0]. fragrance(); f[1]. fragrance(); …
  • 39. Exercise: Inheritance 39 Among the classes that you identified, are there any classes that you can relate via inheritance. (Hint: are there any classes which have common attributes/methods that can be moved up the hierarchy)
  • 40. Revisiting definition 40 Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships. Rama 123 Student • -roll: long • + read(): boolean B.Tech 2010 Course • -name: String • -year: Date • + display(): void • + enroll(Student): boolean enroll() Person • -name: String • + display(): void
  • 41. Summary 41 Object-oriented programming is a method of implementation in which programs are organized as cooperative collections of objects. The object’s state is determined by the value of its properties and its behavior is determined by the operations that it provides. Abstraction is the process of taking only a set of essential characteristics from something. Encapsulation is binding data and operations that work on data together in a construct. Inheritance defines relationship among classes, wherein one class share structure or behavior defined in one or more classes. Polymorphism is using a function in many forms. Poly means ‘many’, Morphism means ‘forms’.
  • 42. Super keyword in java Super keyword is a reference variable that is used for refer parent class object. Super Keyword is mainly used at three level in java At variable level At method level At constructor level Java Basics 42
  • 43. Why use super keyword in java? Whenever inherit base class data into derived class it is chance to get ambiguity, because may be base class and derived class data are same so to difference these data need to use super keyword Java Basics 43
  • 44. Example of Super Keyword class Employee { float salary=10000; } class HR extends Employee { float salary=20000; void display() { System.out.println("Salary: "+super.salary);//print base class salary } } class Supervarible { public static void main(String[] args) { HR obj=new HR(); obj.display(); } } Java Basics 44
  • 45. This keyword in java This keyword is a reference variable that refers the current object in java. This keyword can be used for call current class constructor. The main uses of this keyword is to differentiate the formal parameter and data members of class. o this.show() // method o this.s = s // variable Java Basics 45
  • 47. PROCEDURE • After reading .class file, class loader save the corresponding byte code in the method area. Generally all JVMs have only one method area which is shared across classes which holds information related to each .class file. • Heap is an integral part of JVM memory in which the objects actually rests. JVM produces the Class object for each .class file. • Unlike Heap, Stack is used for storing temporary variables. • PC-Registers used to keep exact information of all instructions (which instruction is executing and which is going to be executed). • A native method used to access the runtime data of the JVM (java virtual machine). Native Method interface enables java code to call by the native applications (programs that are specific to the hardware and OS). Java Basics 47
  • 48. JRE ( Java Runtime Environment ) • Java Runtime Environment is within which the java virtual machine actually runs. JRE contains Java virtual Machine and other files except development tools (debugger and compiler). So developer can run the source code in JRE but he/she cannot develop and compile the code. Java Basics 48
  • 49. JVM ( Java Virtual Machine ) • JVM runs the program by using libraries and files provided by Java Runtime Environment. JDK ( Java Development Kit ) • Java Development Kit can be considered as the super-set of JRE. JDK includes all features that JRE has and over and above it contains development tools such like compiler, debugger etc. Java Basics 49
  • 50. Memory Management  Class(Method) Area Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.  Heap It is the runtime data area in which objects are allocated.  Stack Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.  Class Loader Bootstrap ClassLoader , Extension ClassLoader, System/Application ClassLoader: Java Basics 50
  • 51.  Program Counter Register PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.  Native Method Stack It contains all the native methods used in the application.  Execution Engine It contains: 1. A virtual processor Interpreter 2. Just-In-Time(JIT) compiler  Java Native Interface Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries. Java Basics 51
  • 52. Packages Need for packages What are packages; package declaration in Java Import statement in Java How do packages resolve name clashes? Ex . Package com.main.view package com.main.model package com.main.dto Java Basics 52
  • 53. Miscellenous Double equals operator(==): comaprision toString():to convert the value in string value. Reference variables, local variables, instance variables A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. Java Basics 53
  • 54. 2) Instance Variable A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static. It is called instance variable because its value is instance specific and is not shared among instances. 3) Static variable A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory. Java Basics 54
  • 55. Example class A{ int data=50; //instance variable static int m=100; //static variable void method(){ int n=90; //local variable } } //end of class Java Basics 55
  • 56. Q & A ??? Java Basics 56 For Engineering project please visit mindlabz software