SlideShare a Scribd company logo
Object Oriented
Programming with Java
www.jakir.me
mail@jakir.me
-with Jakir Hossain
Object-oriented
 An object-oriented language is one that is built around the concept of
objects.
 The basic unit of OOP is a class.
 Object-oriented languages allow us to define objects like Car or Mugs and
access their properties in our code.
 We can also send messages to objects, so for my mug I might want to know “Is
it empty?” We can then create and manipulate all sorts of objects to do
different things in our app.
 For example, we can use the Camera object to take a photo. The Camera
object represents the physical camera on an Android phone, but in a way that
we can interact with in code.
 Object can be vertual entity, like our fb account.
Class & Objects
 A Class is a blue print of a particular classification of Objects.
 An Object belongs to a Class of Objects
 An Object is an instrance of a Class.
For Example:
 myCar, khansCar are instances of a class, called Car
 myCat, khansDog are instance of a Class called, Animal.
Class
 class can be visualized as a three-compartment box, as illustrated:
1. Name (or identity): identifies the class.
2. Variables (or attribute, state, field): contains the static attributes of the class.
3. Methods (or behaviors, function, operation): contains the dynamic behaviors of the
class.
Object
 Objects are made up of attributes and methods.
 Objects have a lifespan but classes do not.
 An object is created from a class.
 Object has some Atributes
 Has some Oparation we can to those Atributes
 There are three steps when creating an object from a class:
1. Declaration: A variable declaration with a variable name with an object type.
2. Instantiation: The 'new' key word is used to create the object.
3. Initialization: The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Object Oriended Programming with Java
Naming Conventions
 Leading uppercase letter in class name
public class MyClass {
...
}
 Leading lowercase letter in field, local variable, and method (function) names
 myField, myVar, myMethod
Encapsulation
 Encapsulation means putting together all the variables (instance variables)
and the methods into a single unit called Class.
 It also means hiding data and methods within an Object.
 Encapsulation provides the security that keeps data and methods safe from
inadvertent changes.
 Programmers sometimes refer to encapsulation as using a “black box,” or a
device that you can use without regard to the internal mechanisms. A
programmer can access and use the methods and data contained in the black
box but cannot change them.
Inheritance
 An important feature of object-oriented programs is inheritance—the ability
to create classes that share the attributes and methods of existing classes,
but with more specific features.
 Inheritance is mainly used for code reusability. So you are making use of
already written class and further extending on that.
 We can tell that deriving a new class from existing class, it’s called as
Inheritance.
Inheritance
Polimorphism
 Polymorphism definition is that Poly means many and morphos means forms.
It describes the feature of languages that allows the same word or symbol to
be interpreted correctly in different situations based on the context.
Class Definition
 In Java, we use the keyword class to define a class. For examples:
 Creating Instances of a Class
public class Car{ // class name
int model; // variables
}
Car myCar =new Car();
Defining Methods (Functions Inside Classes)
 Basic method declaration:
public ReturnType methodName(type1 arg1,
type2 arg2, ...) {
...
return(something of ReturnType);
}
 Exception to this format: if you declare the return type as void
 This special syntax that means “this method isn’t going to return a value – it is just
going to do some side effect like printing on the screen”
 In such a case you do not need (in fact, are not permitted), a return statement
that includes a value to be returned
Class with Method
 Without Return Type:
 With Return Type:
public class Car{ // class name
int model; // variables
void printModel() { // Define Method
System.out.println(“Moedl is:”+model);
}
}
public class Car{ // class name
int model; // variables
Int getModel() { // Define Method
return model; // Return a value
}
}
Dot Operator
 The variables and methods belonging to a class are formally called member
variables and member methods. To reference a member variable or method,
we must:
1. first identify the instance you are interested in, and then
2. Use the dot operator (.) to reference the member (variable or method).
Full Example
// File: car.java
public class Car{ // class name
int model; // variables
void printModel(){ // Define Method
System.out.println("Moedl is: "+model);
}
}
// File: cardemo.java
public class CarDemo {
public static void main(String[] args) {
Car newCar = new Car(); // Instantiating Class
newCar.model = 2014; // Assigning Value
newCar.printModel(); // Calling the Method
}
}
Constructors
 Constructors are special functions called when a class is created with
new
 Constructors are especially useful for supplying values of fields
 Constructors are declared through:
public ClassName(args) {
...
}
 Notice that the constructor name must exactly match the class name
 Constructors have no return type (not even void), unlike a regular method
 Java automatically provides a zero-argument constructor if and only if the
class doesn’t define it’s own constructor
 That’s why you could say
Car myCar = new Car();
in the first example, even though a constructor was never defined
The this Variable
 Within an instance method or a constructor, this is a reference
to the current object — the object whose method or
constructor is being called.
 The common uses of the this reference are:
1. To pass a reference to the current object as a parameter to other
methods
someMethod(this);
2. To resolve name conflicts
 Using this permits the use of instance variables in methods that have
local variables with the same name
Full Example
// File: car.java
public class Car{ // class name
int model; // variables
Car(int model){ // Constractor
this.model = model;
}
void printModel(){ // Define Method
System.out.println("Moedl is: "+model);
}
}
// File: cardemo.java
public class CarDemo {
public static void main(String[] args) {
Car newCar = new Car(2014); // Instantiating Class
newCar.printModel(); // Calling the Method
}
}
Some Kye Points
 Class names should start with uppercase; method names with lowercase
 Methods must define a return type or void if no result is returned
 Static methods do not require an instance of the class; static methods can be accessed
through the class name
 The this reference in a class refers to the current object
 Class constructors do not declare a return type
 Override methods - redefine inherited methods
Questions?
Ad

More Related Content

What's hot (20)

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
OOP in C# Classes and Objects.
OOP in C# Classes and Objects.OOP in C# Classes and Objects.
OOP in C# Classes and Objects.
Abid Kohistani
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
Fajar Baskoro
 
Pi j3.2 polymorphism
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison
 
Java basics
Java basicsJava basics
Java basics
Shivanshu Purwar
 
CLASS & OBJECT IN JAVA
CLASS & OBJECT  IN JAVACLASS & OBJECT  IN JAVA
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
siragezeynu
 
Object Oriented Javascript part2
Object Oriented Javascript part2Object Oriented Javascript part2
Object Oriented Javascript part2
Usman Mehmood
 
Classes, objects, methods, constructors, this keyword in java
Classes, objects, methods, constructors, this keyword  in javaClasses, objects, methods, constructors, this keyword  in java
Classes, objects, methods, constructors, this keyword in java
TharuniDiddekunta
 
Variables in python
Variables in pythonVariables in python
Variables in python
Jaya Kumari
 
Objects and Types C#
Objects and Types C#Objects and Types C#
Objects and Types C#
Raghuveer Guthikonda
 
Oops
OopsOops
Oops
Jaya Kumari
 
Classes2
Classes2Classes2
Classes2
phanleson
 
Inheritance
InheritanceInheritance
Inheritance
Pranali Chaudhari
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Oops in java
Oops in javaOops in java
Oops in java
baabtra.com - No. 1 supplier of quality freshers
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
Jacob William
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
Elizabeth alexander
 
Classes and Objects in C#
Classes and Objects in C#Classes and Objects in C#
Classes and Objects in C#
Adeel Rasheed
 

Similar to Object Oriended Programming with Java (20)

Application package
Application packageApplication package
Application package
JAYAARC
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Inocentshuja Ahmad
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
MuhammadHuzaifa981023
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Java oop concepts
Java oop conceptsJava oop concepts
Java oop concepts
Syeful Islam
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
OOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHatOOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
A350103
A350103A350103
A350103
aijbm
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
sandy14234
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyjChapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
dannygriff1
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
Oops
OopsOops
Oops
Sankar Balasubramanian
 
Lecture13 abap on line
Lecture13 abap on lineLecture13 abap on line
Lecture13 abap on line
Milind Patil
 
Object Oriented Programming (Advanced )
Object Oriented Programming   (Advanced )Object Oriented Programming   (Advanced )
Object Oriented Programming (Advanced )
ayesha420248
 
Lecture 4. mte 407
Lecture 4. mte 407Lecture 4. mte 407
Lecture 4. mte 407
rumanatasnim415
 
basic concepts of object oriented programming
basic concepts of object oriented programmingbasic concepts of object oriented programming
basic concepts of object oriented programming
infotechsaasc
 
Application package
Application packageApplication package
Application package
JAYAARC
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Inocentshuja Ahmad
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
Ap Power Point Chpt4
Ap Power Point Chpt4Ap Power Point Chpt4
Ap Power Point Chpt4
dplunkett
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
OOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHatOOPs Interview Questions PDF By ScholarHat
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
rani marri
 
A350103
A350103A350103
A350103
aijbm
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyjChapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Is2215 lecture2 student(2)
Is2215 lecture2 student(2)Is2215 lecture2 student(2)
Is2215 lecture2 student(2)
dannygriff1
 
Lecture13 abap on line
Lecture13 abap on lineLecture13 abap on line
Lecture13 abap on line
Milind Patil
 
Object Oriented Programming (Advanced )
Object Oriented Programming   (Advanced )Object Oriented Programming   (Advanced )
Object Oriented Programming (Advanced )
ayesha420248
 
basic concepts of object oriented programming
basic concepts of object oriented programmingbasic concepts of object oriented programming
basic concepts of object oriented programming
infotechsaasc
 
Ad

Recently uploaded (20)

Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink DisplayHow to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
CircuitDigest
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
DED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedungDED KOMINFO detail engginering design gedung
DED KOMINFO detail engginering design gedung
nabilarizqifadhilah1
 
introduction technology technology tec.pptx
introduction technology technology tec.pptxintroduction technology technology tec.pptx
introduction technology technology tec.pptx
Iftikhar70
 
Slide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptxSlide share PPT of SOx control technologies.pptx
Slide share PPT of SOx control technologies.pptx
vvsasane
 
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink DisplayHow to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
CircuitDigest
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Automatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and BeyondAutomatic Quality Assessment for Speech and Beyond
Automatic Quality Assessment for Speech and Beyond
NU_I_TODALAB
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdfLittle Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
Little Known Ways To 3 Best sites to Buy Linkedin Accounts.pdf
gori42199
 
Ad

Object Oriended Programming with Java

  • 1. Object Oriented Programming with Java www.jakir.me mail@jakir.me -with Jakir Hossain
  • 2. Object-oriented  An object-oriented language is one that is built around the concept of objects.  The basic unit of OOP is a class.  Object-oriented languages allow us to define objects like Car or Mugs and access their properties in our code.  We can also send messages to objects, so for my mug I might want to know “Is it empty?” We can then create and manipulate all sorts of objects to do different things in our app.  For example, we can use the Camera object to take a photo. The Camera object represents the physical camera on an Android phone, but in a way that we can interact with in code.  Object can be vertual entity, like our fb account.
  • 3. Class & Objects  A Class is a blue print of a particular classification of Objects.  An Object belongs to a Class of Objects  An Object is an instrance of a Class. For Example:  myCar, khansCar are instances of a class, called Car  myCat, khansDog are instance of a Class called, Animal.
  • 4. Class  class can be visualized as a three-compartment box, as illustrated: 1. Name (or identity): identifies the class. 2. Variables (or attribute, state, field): contains the static attributes of the class. 3. Methods (or behaviors, function, operation): contains the dynamic behaviors of the class.
  • 5. Object  Objects are made up of attributes and methods.  Objects have a lifespan but classes do not.  An object is created from a class.  Object has some Atributes  Has some Oparation we can to those Atributes  There are three steps when creating an object from a class: 1. Declaration: A variable declaration with a variable name with an object type. 2. Instantiation: The 'new' key word is used to create the object. 3. Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
  • 7. Naming Conventions  Leading uppercase letter in class name public class MyClass { ... }  Leading lowercase letter in field, local variable, and method (function) names  myField, myVar, myMethod
  • 8. Encapsulation  Encapsulation means putting together all the variables (instance variables) and the methods into a single unit called Class.  It also means hiding data and methods within an Object.  Encapsulation provides the security that keeps data and methods safe from inadvertent changes.  Programmers sometimes refer to encapsulation as using a “black box,” or a device that you can use without regard to the internal mechanisms. A programmer can access and use the methods and data contained in the black box but cannot change them.
  • 9. Inheritance  An important feature of object-oriented programs is inheritance—the ability to create classes that share the attributes and methods of existing classes, but with more specific features.  Inheritance is mainly used for code reusability. So you are making use of already written class and further extending on that.  We can tell that deriving a new class from existing class, it’s called as Inheritance.
  • 11. Polimorphism  Polymorphism definition is that Poly means many and morphos means forms. It describes the feature of languages that allows the same word or symbol to be interpreted correctly in different situations based on the context.
  • 12. Class Definition  In Java, we use the keyword class to define a class. For examples:  Creating Instances of a Class public class Car{ // class name int model; // variables } Car myCar =new Car();
  • 13. Defining Methods (Functions Inside Classes)  Basic method declaration: public ReturnType methodName(type1 arg1, type2 arg2, ...) { ... return(something of ReturnType); }  Exception to this format: if you declare the return type as void  This special syntax that means “this method isn’t going to return a value – it is just going to do some side effect like printing on the screen”  In such a case you do not need (in fact, are not permitted), a return statement that includes a value to be returned
  • 14. Class with Method  Without Return Type:  With Return Type: public class Car{ // class name int model; // variables void printModel() { // Define Method System.out.println(“Moedl is:”+model); } } public class Car{ // class name int model; // variables Int getModel() { // Define Method return model; // Return a value } }
  • 15. Dot Operator  The variables and methods belonging to a class are formally called member variables and member methods. To reference a member variable or method, we must: 1. first identify the instance you are interested in, and then 2. Use the dot operator (.) to reference the member (variable or method).
  • 16. Full Example // File: car.java public class Car{ // class name int model; // variables void printModel(){ // Define Method System.out.println("Moedl is: "+model); } } // File: cardemo.java public class CarDemo { public static void main(String[] args) { Car newCar = new Car(); // Instantiating Class newCar.model = 2014; // Assigning Value newCar.printModel(); // Calling the Method } }
  • 17. Constructors  Constructors are special functions called when a class is created with new  Constructors are especially useful for supplying values of fields  Constructors are declared through: public ClassName(args) { ... }  Notice that the constructor name must exactly match the class name  Constructors have no return type (not even void), unlike a regular method  Java automatically provides a zero-argument constructor if and only if the class doesn’t define it’s own constructor  That’s why you could say Car myCar = new Car(); in the first example, even though a constructor was never defined
  • 18. The this Variable  Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called.  The common uses of the this reference are: 1. To pass a reference to the current object as a parameter to other methods someMethod(this); 2. To resolve name conflicts  Using this permits the use of instance variables in methods that have local variables with the same name
  • 19. Full Example // File: car.java public class Car{ // class name int model; // variables Car(int model){ // Constractor this.model = model; } void printModel(){ // Define Method System.out.println("Moedl is: "+model); } } // File: cardemo.java public class CarDemo { public static void main(String[] args) { Car newCar = new Car(2014); // Instantiating Class newCar.printModel(); // Calling the Method } }
  • 20. Some Kye Points  Class names should start with uppercase; method names with lowercase  Methods must define a return type or void if no result is returned  Static methods do not require an instance of the class; static methods can be accessed through the class name  The this reference in a class refers to the current object  Class constructors do not declare a return type  Override methods - redefine inherited methods
  翻译: