SlideShare une entreprise Scribd logo
1  sur  16
JAVA
P.Prathibha
Topics for Today’s Session
About JAVA
Creating Classes and Objects
Command line arguments
How to Create class and Object
Java
 Java is a computing platform for application
development and an object-oriented,
 Java is Class-based and Concurrent programming
language
 It means the code can be executed by multiple
processes at the same time.
 Java can run on all platforms and free to access.
 Java is Simple, Secure, Robust, Complete Object
oriented and Platform Independent High level
Language
 It is Portable and Multi-thread technology gives
High Performance.
Objects and Classes in Java
 An object in Java is the physical as well as a logical entity, whereas, a class in Java is a
logical entity only.
 An entity that has state and behavior is known as an object e.g., chair, bike, pen, table,
car, etc.
 It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
 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 : An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each
object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is Blue, known as its state. It is used to
write, so writing is its behavior.
Identity State / Attributes
Breed
Color
Age
Behaviours
Bark
Eat
Sleep
Bite
 An object is an instance of a class. A class is a template or blueprint from
which objects are created. So, an object is the instance(result) of a class.
Object Definitions:
 An object is a real-world entity.
 An object is a runtime entity.
 The object is an entity which has state and behavior.
 The object is an instance of a class.
Class
 A class is a group of objects which have common properties.
 It is a template or blueprint from which objects are created.
 It is a logical entity. It can't be physical.


 A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
Create a Class






 Example: Create a class named "MyClass" with a variable a:
Class classname [extends superclassname]
{
[variable/field declaration];
[methods declaration];
}
class MyClass
{
int a = 5;
}
Here
Everything inside the brackets is optional.
classname and superclassname are any valid java identifiers.
The keyword extends indicate that the properties of the superclass name are
extended to the classname class.
This concept is known as Inheritance.
Fields declaration:
 Data is encapsulated in a class by placing data fields in the
class. These variables are called “instance variables”.
 These are declared just as local variables;
Methods Declaration:
 A class with only data fields has no life. Such classes cannot
respond to any messages.
 We must add methods that are useful for manipulating the data
of the class.
 Methods for a class are declared inside the body of the class
but immediately after the declaration of the variables.
Type methodname (parameter list)
{
method_body;
}
Method declaration having four parts:
1. The name of the method ( method name) (It is any
valid identifier)
2. The type of the value of the method returns (type)
(it is any valid data type, it is void when it does not
return any value.)
3. A list of parameters (parameter list) (This list
contains variable names and types of all the values
we want to send as input, when no input data are
required, we must use empty parentheses)
4. The body of the method. It describes the operations
to be performed on the data.
Example: : int sum (int a, int b)
{
c=a+b;
return c;
Method in Java
 In Java, a method is like a
function which is used to
expose the behavior of an
object.
 Advantage of Method
 Code Reusability
 Code Optimization
Local variables
Instance variable




Class variables
.
Example
class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Creating Objects:
 An object is a block of memory that contains space to store all the
instance variables.
 An object is a software entity (unit) that combines a set of data with
set of operations to manipulate that data.
 A class defines a type of object. i.e., each object belongs to some class
object is also called as an instance.
 Java has an operator new to create objects. Creating an object is also
referred to as instantiating an object.
 Objects in java can be created by using the syntax.
Syntax:
Classname objname;
Objname = new classname();
 The first statement declares a variable to hold
the object reference and second one actually
assigns the object reference to the variable.
 Ex
triangle tri1; // declaring the object)
Tri1 = new triangle //instantiating the object)
The above two statements are combined into a
single statement as
Triangle tri1 = new triangle();
Accessing class Members: every object contains its own set of variables.
 We should assign values to these variables in order to use them in our
program.
 When we are outside the class we cannot access the instance variables and
methods directly. For this we use dot operator.
objectname.varaiblename = value;
objectname.methodname (parameter list);
Example: tri1.length = 15;
tri2.length = 20;
tri1.getData( 20,30)
public class MyClass {
int a = 5;
public static void main(String[]
args) {
MyClass myObj = new
MyClass();
System.out.println(myObj.a);
}
}
Ex: A java program to demonstrate application ofclasses, objects and methods.(Pra.Prog. 17)
class triangle {
int length, width;
void getData(int x, int y)
{
length = x;
width= y;
}
int triarea( )
{
int area = (length * width)/2;
return(area);
}
}
class triarea {
public static void main (String args[ ])
{
int area1, area2;
triangle tri1 = new triangle();
triangle tri2 = new triangle();
tri1.length= 20;
tri1.width = 30;
area1 =( tri1.length * tri1.width)/2;
tri2.getData( 10, 15);
area2 = tri2.triarea();
System.out.println( "area1 = " + area1);
System.out.println( "area2 = " + area2);
}
}
Instance variables declared in a single
line
getData is a method, it does not return any value
so its type is void, we are passing two integer
values and they are assigned to length and width
triarea is another method, it returns a value of
data type int. We are not passing values, so
the parameter list is empty
class with main method
Creating objects
Accessing variables
Accessing Methods
Command line Arguments
 The java command-line argument is an argument i.e. passed at the time of running the java
program.
 A Java application can accept any number of arguments from the command line.
 The String array stores all the arguments passed through the command line.
 Arguments are always stored as strings and always separated by white-space.
// Example using Commandline arguments
class Cmdargs {
public static void main(String[] args) {
System.out.println("Command-Line arguments
are");
// loop through all arguments
for(String str: args) {
System.out.println(str);
}
} }
1. To compile the code
javac Cmdargs.java
2. To run the code
java Cmdargs
Now suppose we want to pass some arguments
while running the program,
we can pass the arguments after the class name. For
example,
java Main apple ball cat
output.
Command-Line arguments are
Apple
Ball
Cat
// Program to check for command line arguments
class Hello {
public static void main(String[] args) {
// check if length of args array is greater than 0
if (args.length > 0) {
System.out.println("The command line"+ " arguments are:");
// iterating the args array and printing the command line arguments
for (String s:args)
System.out.println(s);
}
else
System.out.println("No command line "+ "arguments found.");
} }
javac Hello.java
java Hello Lion Dog Cat Elephant
Output:
The Command-Line arguments are
Lion
Dog
Cat
Elephant
javac Hello.java
java Hello
Output
No Command-Line arguments
foun





Classes objects in java

Contenu connexe

Tendances

Tendances (20)

Packages in java
Packages in javaPackages in java
Packages in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Java threads
Java threadsJava threads
Java threads
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Interface in java
Interface in javaInterface in java
Interface in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 

Similaire à 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-argumentSuresh Mohta
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)Khaled Anaqwa
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptmanomkpsg
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2Raghu nath
 
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
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java ProgrammingMath-Circle
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorialGhulam Abbas Khan
 

Similaire à Classes objects in java (20)

Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
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
 
Android Training (Java Review)
Android Training (Java Review)Android Training (Java Review)
Android Training (Java Review)
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Java notes
Java notesJava notes
Java notes
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Java_Interview Qns
Java_Interview QnsJava_Interview Qns
Java_Interview Qns
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
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
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Oops
OopsOops
Oops
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Object oriented programming tutorial
Object oriented programming tutorialObject oriented programming tutorial
Object oriented programming tutorial
 

Plus de Madishetty Prathibha

Plus de Madishetty Prathibha (13)

Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Types of datastructures
Types of datastructuresTypes of datastructures
Types of datastructures
 
Introduction to algorithms
Introduction to algorithmsIntroduction to algorithms
Introduction to algorithms
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Java features
Java  features Java  features
Java features
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 

Dernier

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 

Dernier (20)

Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 

Classes objects in java

  • 2. Topics for Today’s Session About JAVA Creating Classes and Objects Command line arguments How to Create class and Object
  • 3. Java  Java is a computing platform for application development and an object-oriented,  Java is Class-based and Concurrent programming language  It means the code can be executed by multiple processes at the same time.  Java can run on all platforms and free to access.  Java is Simple, Secure, Robust, Complete Object oriented and Platform Independent High level Language  It is Portable and Multi-thread technology gives High Performance.
  • 4. Objects and Classes in Java  An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.  An entity that has state and behavior is known as an object e.g., chair, bike, pen, table, car, etc.  It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.  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 : An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely. For Example, Pen is an object. Its name is Reynolds; color is Blue, known as its state. It is used to write, so writing is its behavior. Identity State / Attributes Breed Color Age Behaviours Bark Eat Sleep Bite
  • 5.  An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class. Object Definitions:  An object is a real-world entity.  An object is a runtime entity.  The object is an entity which has state and behavior.  The object is an instance of a class.
  • 6. Class  A class is a group of objects which have common properties.  It is a template or blueprint from which objects are created.  It is a logical entity. It can't be physical.    A class in Java can contain:  Fields  Methods  Constructors  Blocks  Nested class and interface
  • 7. Create a Class        Example: Create a class named "MyClass" with a variable a: Class classname [extends superclassname] { [variable/field declaration]; [methods declaration]; } class MyClass { int a = 5; } Here Everything inside the brackets is optional. classname and superclassname are any valid java identifiers. The keyword extends indicate that the properties of the superclass name are extended to the classname class. This concept is known as Inheritance.
  • 8. Fields declaration:  Data is encapsulated in a class by placing data fields in the class. These variables are called “instance variables”.  These are declared just as local variables; Methods Declaration:  A class with only data fields has no life. Such classes cannot respond to any messages.  We must add methods that are useful for manipulating the data of the class.  Methods for a class are declared inside the body of the class but immediately after the declaration of the variables. Type methodname (parameter list) { method_body; } Method declaration having four parts: 1. The name of the method ( method name) (It is any valid identifier) 2. The type of the value of the method returns (type) (it is any valid data type, it is void when it does not return any value.) 3. A list of parameters (parameter list) (This list contains variable names and types of all the values we want to send as input, when no input data are required, we must use empty parentheses) 4. The body of the method. It describes the operations to be performed on the data. Example: : int sum (int a, int b) { c=a+b; return c; Method in Java  In Java, a method is like a function which is used to expose the behavior of an object.  Advantage of Method  Code Reusability  Code Optimization
  • 10. Example class Dog { String breed; int age; String color; void barking() { } void hungry() { } void sleeping() { } } Creating Objects:  An object is a block of memory that contains space to store all the instance variables.  An object is a software entity (unit) that combines a set of data with set of operations to manipulate that data.  A class defines a type of object. i.e., each object belongs to some class object is also called as an instance.  Java has an operator new to create objects. Creating an object is also referred to as instantiating an object.  Objects in java can be created by using the syntax. Syntax: Classname objname; Objname = new classname();  The first statement declares a variable to hold the object reference and second one actually assigns the object reference to the variable.  Ex triangle tri1; // declaring the object) Tri1 = new triangle //instantiating the object) The above two statements are combined into a single statement as Triangle tri1 = new triangle();
  • 11. Accessing class Members: every object contains its own set of variables.  We should assign values to these variables in order to use them in our program.  When we are outside the class we cannot access the instance variables and methods directly. For this we use dot operator. objectname.varaiblename = value; objectname.methodname (parameter list); Example: tri1.length = 15; tri2.length = 20; tri1.getData( 20,30) public class MyClass { int a = 5; public static void main(String[] args) { MyClass myObj = new MyClass(); System.out.println(myObj.a); } }
  • 12. Ex: A java program to demonstrate application ofclasses, objects and methods.(Pra.Prog. 17) class triangle { int length, width; void getData(int x, int y) { length = x; width= y; } int triarea( ) { int area = (length * width)/2; return(area); } } class triarea { public static void main (String args[ ]) { int area1, area2; triangle tri1 = new triangle(); triangle tri2 = new triangle(); tri1.length= 20; tri1.width = 30; area1 =( tri1.length * tri1.width)/2; tri2.getData( 10, 15); area2 = tri2.triarea(); System.out.println( "area1 = " + area1); System.out.println( "area2 = " + area2); } } Instance variables declared in a single line getData is a method, it does not return any value so its type is void, we are passing two integer values and they are assigned to length and width triarea is another method, it returns a value of data type int. We are not passing values, so the parameter list is empty class with main method Creating objects Accessing variables Accessing Methods
  • 13. Command line Arguments  The java command-line argument is an argument i.e. passed at the time of running the java program.  A Java application can accept any number of arguments from the command line.  The String array stores all the arguments passed through the command line.  Arguments are always stored as strings and always separated by white-space. // Example using Commandline arguments class Cmdargs { public static void main(String[] args) { System.out.println("Command-Line arguments are"); // loop through all arguments for(String str: args) { System.out.println(str); } } } 1. To compile the code javac Cmdargs.java 2. To run the code java Cmdargs Now suppose we want to pass some arguments while running the program, we can pass the arguments after the class name. For example, java Main apple ball cat output. Command-Line arguments are Apple Ball Cat
  • 14. // Program to check for command line arguments class Hello { public static void main(String[] args) { // check if length of args array is greater than 0 if (args.length > 0) { System.out.println("The command line"+ " arguments are:"); // iterating the args array and printing the command line arguments for (String s:args) System.out.println(s); } else System.out.println("No command line "+ "arguments found."); } } javac Hello.java java Hello Lion Dog Cat Elephant Output: The Command-Line arguments are Lion Dog Cat Elephant javac Hello.java java Hello Output No Command-Line arguments foun