SlideShare a Scribd company logo
1 of 28
UNIT 3-CLASS
 Classes and Objects are basic concepts of Object Oriented Programming
which revolve around the real life entities.
 A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to
all objects of one type. In general, class declarations can include these
components.
 Modifiers : A class can be public or has default access.
 Class name: The name should capitalized by convention.
 Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
 Interfaces(if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
 Body: The class body surrounded by braces, { }.
 Constructors are used for initializing new objects.
 Fields are variables that provides the state of the class and its objects
 methods are used to implement the behavior of the class and its objects.
CLASS
 It is a basic unit of Object Oriented Programming and represents the
real life entities. A typical Java program creates many objects, which
as you know, interact by invoking methods. An object consists of :
 State : It is represented by attributes of an object. It also reflects the
properties of an object.
 Behavior : It is represented by methods of an object. It also reflects the
response of an object with other objects.
 Identity : It gives a unique name to an object and enables one object to
interact with other objects.
 Ex: car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
 When an object of a class is created, the class is said to
be instantiated.
 All the instances share the attributes and the behavior of the class. But
the values of those attributes, i.e. the state are unique for each object.
 A single class may have any number of instances.
OBJECT
public class MyClass
{
int x = 5;
public static void main(String[] args)
{
MyClass myObj = new MyClass();//creating object
System.out.println(myObj.x);
}
}
 The objects that are not referenced anymore will be destroyed
by Garbage Collector of java.
CREATING THE CLASS AND OBJECT
public class MyClass
{
int x = 5;
}
 Member variables in a
class—these are
called fields/attribute
.
 Variables in a method
or block of code—
these are called local
variables.
class OtherClass
{
public static void main(String[] args)
{
MyClass myObj = new MyClass();
System.out.println(myObj.x);
myObj.x=25;
System.out.println(myObj.x);
}
}
 By Reference
public class MyClass
{
int x = 5;
public static void main(String[] args)
{
MyClass myObj = new MyClass();//creating object
System.out.println(myObj.x);
myObj.x=25;
System.out.println(myObj.x);
}
}
3 WAYS TO INITIALIZE OBJECT
 Initialize through methods
Class MyClass{
int i;
void setValue(int x){
i=x;
}
void getValue()
{
System.out.println(i);
}
Public static void main(String[] arg)
{
MyClass myobj1=new MyClass();
myobj1.setValue(10);
myobj1.getValue();
}
}
 Using Constructors:
Class MyClass{
int i;
MyClass()
{
i=10;
}
Public static void main(String[] arg)
{
MyClass myobj1=new MyClass();
System.out.println(myobj1.i);
}
}
 The name must not contain any white spaces.
 The name should not start with special characters like & (ampersand), $ (dollar), _
(underscore).
 Class
• It should start with the uppercase letter.
• It should be a noun such as Color, Button, System, Thread, etc.
• Use appropriate words, instead of acronyms.
Example: - public class Employee { //code snippet }
 Interface
• It should start with the uppercase letter.
• It should be an adjective such as Runnable, Remote, ActionListener.
• Use appropriate words, instead of acronyms.
Example: - interface Printable { //code snippet }
 Method
 • It should start with lowercase letter.
 • It should be a verb such as main(), print(), println().
 • If the name contains multiple words, start it with a lowercase letter followed by
an uppercase letter such as actionPerformed().
JAVA NAMING CONVENTIONS
 Variable
• It should start with a lowercase letter such as id, name.
• It should not start with the special characters like & (ampersand), $
(dollar), _ (underscore).
• If the name contains multiple words, start it with the lowercase letter
followed by an uppercase letter such as firstName, lastName.
• Avoid using one-character variables such as x, y, z.
 Package
• It should be a lowercase letter such as java, lang.
• If the name contains multiple words, it should be separated by dots (.)
such as java.util, java.lang.
 Constant
• It should be in uppercase letters such as RED, YELLOW.
• If the name contains multiple words, it should be separated by an
underscore(_) such as MAX_PRIORITY.
• It may contain digits but not as the first letter.
CONTD…
 Private: The access level of a private modifier is only within
the class. It cannot be accessed from outside the class.
 Default: The access level of a default modifier is only within
the package. It cannot be accessed from outside the package.
If you do not specify any access level, it will be the default.
 Protected: The access level of a protected modifier is within
the package and outside the package through child class. If
you do not make the child class, it cannot be accessed from
outside the package.
 Public: The access level of a public modifier is everywhere. It
can be accessed from within the class, outside the class,
within the package and outside the package.
ACCESS SPECIFIERS
 A constructor in Java is a special method that is used to initialize
objects.
 The constructor is called when an object(instance) of a class is
created. It can be used to set initial values for object attributes
 At the time of calling constructor, memory for the object is
allocated in the memory.
 Every time an object is created using the new() keyword, at least
one constructor is called.
 Constructors can take parameters
 Constructor name must be the same as its class name
 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and
synchronized(non access specifier)
 Constructors can be overloaded.
JAVA CONSTRUCTORS
// Create a MyClass
class public class MyClass
{
int x; // Create a instance variable
// Create a class constructor for the MyClass
MyClass()
{
x = 5; // Set the initial value for the instance variable x
}
public static void main(String[] args)
{
MyClass myObj = new MyClass(); // Create an object of class
MyClass (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
public class MyClass {
int x;
public MyClass(int y) {
x = y;
}
public static void main(String[] args) {
MyClass myObj = new MyClass(5);
System.out.println(myObj.x);
}
}
 A command-line argument is an information that directly follows
the program's name on the command line when it is executed.
 The command-line arguments are stored as strings in the String
array passed to main( ).
public class Echo {
public static void main (String[] args)
{
for (String s: args)
{
System.out.println(s);
}
}
}
COMMAND LINE ARGUMENTS
 public class CommandLine {
public static void main(String[] args)
{
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Command line arguments are strings to parse it following
methods can be used:
ParseInt()
parseFloat()
parseDouble()
 A variable provides us with named storage that our programs can
manipulate. Java provides three types of variables.
 Class variables − Class variables also known as static variables
are declared with the static keyword in a class, but outside a
method, constructor or a block. There would only be one copy of
each class variable per class, regardless of how many objects
are created from it.
 Instance variables − Instance variables are declared in a class,
but outside a method. When space is allocated for an object in
the heap, a slot for each instance variable value is created.
Instance variables hold values that must be referenced by more
than one method, constructor or block, or essential parts of an
object's state that must be present throughout the class.
 Local variables − Local variables are declared in methods,
constructors, or blocks. Local variables are created when the
method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor, or block.
VARIABLES
 A static variable is common to all the instances (or objects) of the class. i.e)only a
single copy of static variable is created and shared among all the instances of the
class. Memory allocation for such variables only happens once when the class is
loaded in the memory..
 Static variable Syntax: static data_type variable_name
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1 .increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count );//2
System.out.println("Obj2: count is="+obj2.count);
}
}
STATIC VARIABLE
public class VariableExample{
int myVariable;
static int data = 30;
public static void main(String args[]){
int a = 100;
VariableExample obj = new VariableExample();
System.out.println("Value of instance variable myVariable:
"+obj.myVariable);
System.out.println("Value of static variable data:
"+VariableExample.data);
System.out.println("Value of local variable a: "+a);
}
}
 Whenever we declare variable as static, then at the class level a single
variable is created which is shared with the objects. Any change in that
static variable reflect to the other objects operations.
 If we won’t initialize a static variable, then by default JVM will provide
a default value for static variable.
 The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
 variable
 method
 class
 The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable.
 It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will
have detailed learning of these.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run(); // compile time error
}
}//end of class
 If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
 If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
 The native keyword is applied to a method to indicate that the
method is implemented in native code using JNI (Java Native
Interface). native is a modifier applicable only for
methods and we can’t apply it anywhere else. The methods
which are implemented in C, C++ are called as native
methods or foreign methods.
 The main objectives of native keyword are:
 To improve performance of the system.
 To achieve machine level/memory level communication.
 To use already existing legacy non-java code.
NATIVE
Class Native
{
Public native void m();
}
Class Test
{
Public static void main(String[] args)
{
Native n = new Native();
n.m();
}
}
 Important points about native keyword:
 For native methods implementation is already available in old languages like C,
C++ and we are not responsible to provide implementation. Hence native method
declaration should end with ; (semi-colon).
 We can’t declare native method as abstract.
 The main advantage of native keyword is improvement in performance but the main
disadvantage of native keyword is that it breaks platform independent nature of
java.
 The Java volatile keyword is used to mark a Java variable as "being
stored in main memory".
 Every read of a volatile variable will be read from the computer's
main memory, and not from the CPU cache, and that every write to
a volatile variable will be written to main memory, and not just to
the CPU cache.
public class SharedObject
{
public volatile int counter = 0;
}
VOLATILE
 Multi-threaded programs may often come to a situation where multiple threads try
to access the same resources and finally produce erroneous and unforeseen results.
 So it needs to be made sure by some synchronization method that only one thread
can access the resource at a given point of time.
 . Synchronized blocks in Java are marked with the synchronized keyword. A
synchronized block in Java is synchronized on some object. All synchronized blocks
synchronized on the same object can only have one thread executing inside them at
a time. All other threads attempting to enter the synchronized block are blocked
until the thread inside the synchronized block exits the block.
 Following is the general form of a synchronized block:
 // Only one thread can execute at a time.The code is said to be synchronized on
 // the monitor object
 synchronized(sync_object)
 {
 // Access shared variables and other
 // shared resources
 }
 This synchronization is implemented in Java with a concept called monitors. Only
one thread can own a monitor at a given time. When a thread acquires a lock, it is
said to have entered the monitor. All other threads attempting to enter the locked
monitor will be suspended until the first thread exits the monitor.
SYNCHRONIZED

More Related Content

What's hot

Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMmanish kumar
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Javakjkleindorfer
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introductionSohanur63
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphismmcollison
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objectskjkleindorfer
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interfacemanish kumar
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 

What's hot (20)

Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Java session4
Java session4Java session4
Java session4
 
Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 
Week9 Intro to classes and objects in Java
Week9 Intro to classes and objects in JavaWeek9 Intro to classes and objects in Java
Week9 Intro to classes and objects in Java
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Week10 packages using objects in objects
Week10 packages using objects in objectsWeek10 packages using objects in objects
Week10 packages using objects in objects
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Lecture 8 abstract class and interface
Lecture   8 abstract class and interfaceLecture   8 abstract class and interface
Lecture 8 abstract class and interface
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 

Similar to Unit3 part1-class

Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMambikavenkatesh2
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer ProgrammingInocentshuja Ahmad
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptmanomkpsg
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
 

Similar to Unit3 part1-class (20)

Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
C# program structure
C# program structureC# program structure
C# program structure
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Oops
OopsOops
Oops
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Lecture22.23.07.2014
Lecture22.23.07.2014Lecture22.23.07.2014
Lecture22.23.07.2014
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
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
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Only oop
Only oopOnly oop
Only oop
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
Java basics
Java basicsJava basics
Java basics
 

More from DevaKumari Vijay

More from DevaKumari Vijay (16)

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
 
Os ch1
Os ch1Os ch1
Os ch1
 
Unit2
Unit2Unit2
Unit2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
 
Decisiontree&amp;game theory
Decisiontree&amp;game theoryDecisiontree&amp;game theory
Decisiontree&amp;game theory
 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
 
Operations research lpp
Operations research lppOperations research lpp
Operations research lpp
 

Recently uploaded

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
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
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
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
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Recently uploaded (20)

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"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
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
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.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
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

Unit3 part1-class

  • 2.  Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.  A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components.  Modifiers : A class can be public or has default access.  Class name: The name should capitalized by convention.  Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.  Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.  Body: The class body surrounded by braces, { }.  Constructors are used for initializing new objects.  Fields are variables that provides the state of the class and its objects  methods are used to implement the behavior of the class and its objects. CLASS
  • 3.  It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of :  State : It is represented by attributes of an object. It also reflects the properties of an object.  Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects.  Identity : It gives a unique name to an object and enables one object to interact with other objects.  Ex: car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.  When an object of a class is created, the class is said to be instantiated.  All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object.  A single class may have any number of instances. OBJECT
  • 4. public class MyClass { int x = 5; public static void main(String[] args) { MyClass myObj = new MyClass();//creating object System.out.println(myObj.x); } }  The objects that are not referenced anymore will be destroyed by Garbage Collector of java. CREATING THE CLASS AND OBJECT
  • 5. public class MyClass { int x = 5; }  Member variables in a class—these are called fields/attribute .  Variables in a method or block of code— these are called local variables. class OtherClass { public static void main(String[] args) { MyClass myObj = new MyClass(); System.out.println(myObj.x); myObj.x=25; System.out.println(myObj.x); } }
  • 6.  By Reference public class MyClass { int x = 5; public static void main(String[] args) { MyClass myObj = new MyClass();//creating object System.out.println(myObj.x); myObj.x=25; System.out.println(myObj.x); } } 3 WAYS TO INITIALIZE OBJECT
  • 7.  Initialize through methods Class MyClass{ int i; void setValue(int x){ i=x; } void getValue() { System.out.println(i); } Public static void main(String[] arg) { MyClass myobj1=new MyClass(); myobj1.setValue(10); myobj1.getValue(); } }
  • 8.  Using Constructors: Class MyClass{ int i; MyClass() { i=10; } Public static void main(String[] arg) { MyClass myobj1=new MyClass(); System.out.println(myobj1.i); } }
  • 9.  The name must not contain any white spaces.  The name should not start with special characters like & (ampersand), $ (dollar), _ (underscore).  Class • It should start with the uppercase letter. • It should be a noun such as Color, Button, System, Thread, etc. • Use appropriate words, instead of acronyms. Example: - public class Employee { //code snippet }  Interface • It should start with the uppercase letter. • It should be an adjective such as Runnable, Remote, ActionListener. • Use appropriate words, instead of acronyms. Example: - interface Printable { //code snippet }  Method  • It should start with lowercase letter.  • It should be a verb such as main(), print(), println().  • If the name contains multiple words, start it with a lowercase letter followed by an uppercase letter such as actionPerformed(). JAVA NAMING CONVENTIONS
  • 10.  Variable • It should start with a lowercase letter such as id, name. • It should not start with the special characters like & (ampersand), $ (dollar), _ (underscore). • If the name contains multiple words, start it with the lowercase letter followed by an uppercase letter such as firstName, lastName. • Avoid using one-character variables such as x, y, z.  Package • It should be a lowercase letter such as java, lang. • If the name contains multiple words, it should be separated by dots (.) such as java.util, java.lang.  Constant • It should be in uppercase letters such as RED, YELLOW. • If the name contains multiple words, it should be separated by an underscore(_) such as MAX_PRIORITY. • It may contain digits but not as the first letter. CONTD…
  • 11.  Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.  Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.  Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.  Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. ACCESS SPECIFIERS
  • 12.
  • 13.  A constructor in Java is a special method that is used to initialize objects.  The constructor is called when an object(instance) of a class is created. It can be used to set initial values for object attributes  At the time of calling constructor, memory for the object is allocated in the memory.  Every time an object is created using the new() keyword, at least one constructor is called.  Constructors can take parameters  Constructor name must be the same as its class name  A Constructor must have no explicit return type  A Java constructor cannot be abstract, static, final, and synchronized(non access specifier)  Constructors can be overloaded. JAVA CONSTRUCTORS
  • 14. // Create a MyClass class public class MyClass { int x; // Create a instance variable // Create a class constructor for the MyClass MyClass() { x = 5; // Set the initial value for the instance variable x } public static void main(String[] args) { MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the constructor) System.out.println(myObj.x); // Print the value of x } }
  • 15. public class MyClass { int x; public MyClass(int y) { x = y; } public static void main(String[] args) { MyClass myObj = new MyClass(5); System.out.println(myObj.x); } }
  • 16.  A command-line argument is an information that directly follows the program's name on the command line when it is executed.  The command-line arguments are stored as strings in the String array passed to main( ). public class Echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } } COMMAND LINE ARGUMENTS
  • 17.  public class CommandLine { public static void main(String[] args) { for(int i = 0; i<args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } } } Command line arguments are strings to parse it following methods can be used: ParseInt() parseFloat() parseDouble()
  • 18.  A variable provides us with named storage that our programs can manipulate. Java provides three types of variables.  Class variables − Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.  Instance variables − Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.  Local variables − Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. VARIABLES
  • 19.  A static variable is common to all the instances (or objects) of the class. i.e)only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory..  Static variable Syntax: static data_type variable_name class VariableDemo { static int count=0; public void increment() { count++; } public static void main(String args[]) { VariableDemo obj1=new VariableDemo(); VariableDemo obj2=new VariableDemo(); obj1 .increment(); obj2.increment(); System.out.println("Obj1: count is="+obj1.count );//2 System.out.println("Obj2: count is="+obj2.count); } } STATIC VARIABLE
  • 20. public class VariableExample{ int myVariable; static int data = 30; public static void main(String args[]){ int a = 100; VariableExample obj = new VariableExample(); System.out.println("Value of instance variable myVariable: "+obj.myVariable); System.out.println("Value of static variable data: "+VariableExample.data); System.out.println("Value of local variable a: "+a); } }
  • 21.  Whenever we declare variable as static, then at the class level a single variable is created which is shared with the objects. Any change in that static variable reflect to the other objects operations.  If we won’t initialize a static variable, then by default JVM will provide a default value for static variable.  The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:  variable  method  class  The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable.  It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these.
  • 22. class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); // compile time error } }//end of class
  • 23.  If you make any method as final, you cannot override it. class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } }
  • 24.  If you make any class as final, you cannot extend it. final class Bike{} class Honda1 extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } }
  • 25.  The native keyword is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface). native is a modifier applicable only for methods and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called as native methods or foreign methods.  The main objectives of native keyword are:  To improve performance of the system.  To achieve machine level/memory level communication.  To use already existing legacy non-java code. NATIVE
  • 26. Class Native { Public native void m(); } Class Test { Public static void main(String[] args) { Native n = new Native(); n.m(); } }  Important points about native keyword:  For native methods implementation is already available in old languages like C, C++ and we are not responsible to provide implementation. Hence native method declaration should end with ; (semi-colon).  We can’t declare native method as abstract.  The main advantage of native keyword is improvement in performance but the main disadvantage of native keyword is that it breaks platform independent nature of java.
  • 27.  The Java volatile keyword is used to mark a Java variable as "being stored in main memory".  Every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache. public class SharedObject { public volatile int counter = 0; } VOLATILE
  • 28.  Multi-threaded programs may often come to a situation where multiple threads try to access the same resources and finally produce erroneous and unforeseen results.  So it needs to be made sure by some synchronization method that only one thread can access the resource at a given point of time.  . Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.  Following is the general form of a synchronized block:  // Only one thread can execute at a time.The code is said to be synchronized on  // the monitor object  synchronized(sync_object)  {  // Access shared variables and other  // shared resources  }  This synchronization is implemented in Java with a concept called monitors. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. SYNCHRONIZED