SlideShare a Scribd company logo
    Module 2   Object-Oriented Programming
  Objectives   •  Define modeling concepts: abstraction, encapsulation. •  Define class, member, attribute, method, constructor  and  package   •  Invoke a method on a particular object. •  In a Java program, identify the following: The package statement.  The import statements.  Classes, methods, and attributes.  Constructors.  •   Use the Java API online documentation
Abstraction An essential element of object oriented language is abstraction. Humans manage the complexity through abstraction. For example People do not think of car as a set of tens of thousand of individual  parts. They think of it as a well defined object with its own unique  behavior. They can ignore the details of how the engine, transmission  and braking systems work. Powerful way to manage the abstraction is through the use of  hierarchical classifications.
From the outside, the car is a single object.  Once inside you see that the car consist of several subsystems:  steering, brakes, sound system, seat belts ,cellular system and so on.  In turn each of these subsystem is made up of more specialized units. For example sound system consist of a radio, a CD player and a tape  player. The point is you manage the complexity of car through the use of  hierarchical abstraction.
Hierarchical abstraction of complex systems can also be  applied to computer programs.  The data from program can be transformed by abstraction into its  component objects.  Each object describe its own unique behavior.We can treat these  objects as concrete entities that respond to message telling them to  do something.
Real-world  Object s   Real-world objects are your dog, your desk,  your television set, your bicycle .   These real-world objects share two characteristics:   They all have  state  and  behavior .   For example,  dogs have state (name, color, breed, hungry)  and behavior (barking, fetching, and wagging tail).
Software objects Software objects are modeled after real-world  objects in that they too have state and behavior.  A software object maintains its state in one or more  variables.  A variable is an item of data named by an identifier.  A software object implements its behavior with  methods.
Classes as Blueprints for Objects •  In manufacturing, a blueprint is a description of a device  from which many physical devices are constructed. •  In software, a class is a description of an object:    A class describes the data that each object includes    A class describes the behaviors that each object exhibits  •  In Java, classes support three key features of OOP   encapsulation  inheritance polymorphism
Objects versus Classes In the real world, it's obvious that classes are not  themselves the objects they describe:  A blueprint of a bicycle is not a bicycle.
The Life Cycle of an Object   Life cycle of an object involves 1.Creating Objects. 2.Using Objects. 3.Cleaning up unused objects.
Creating Objects This statement creates a new Rectangle object from the Rectangle  class. Rectangle rect = new Rectangle();  This single statement performs three actions:  Declaration : Rectangle rect is a variable declaration that declares  to the compiler that the name rect will be used to refer to a Rectangle  object. Instantiation : new is a Java operator that creates the new object  Initialization : Rectangle() is a call to Rectangle's constructor,  which initializes the object.
Using Objects   Once you've created an object, you probably want to use it  for something.  You may need information from it, want to change its state, or have  it perform some action.  Objects give you two ways to do these things:  1.Manipulate or inspect its variables .  area = rect.height * rect.width;  2.Call its methods.   rect.move(15, 37);
Cleaning Up Unused Objects   Java allows you to create as many objects as you want  and you never have to worry about destroying them. The Java runtime  environment deletes objects when it determines that they are no longer  being used. This process is called  garbage collection. An object is eligible for garbage collection when there are no more  references to that object. The Java platform has a garbage collector that periodically frees  the memory used by objects that are no longer needed.   The garbage collector runs in a low-priority thread
Finalization Before an object gets garbage-collected, the garbage collector  gives the object an opportunity to clean up after itself through a call to  the object's finalize method. This process is known as  finalization .   During finalization, an object may wish to free system resources  such as files and sockets or to drop references to other objects so  that they in turn become eligible for garbage collection.
Key Features of OOPs 1. Inheritanc e 2.Encapsulation 3.P olymorphism
Inheritanc e I nheritance  is a  mechanism  that enables one class to inherit  all of the behaviour and attributes of another class.   For example, mountain bikes, road bikes, are all kinds of bicycles. Mountain bikes, road bikes are all subclasses of the bicycle class.  Similarly, the bicycle class is the superclass of mountain bikes,  road bikes. Each subclass inherits state from the superclass.   Mountain bikes, road bikes share some states: cadence, speed, and  the like. Also, each subclass inherits methods from the superclass.  Example  inheritance.java
Encapsulation •   Encapsulation means shielding   •  The localization of knowledge within a module.   •  Hides the implementation details of a class.  •  Makes the code more maintainable
Encapsulation in Java In Java the basis of encapsulation is the class. Since the purpose of a class is to encapsulate complexity,  there are mechanisms for hiding the complexity of the  implementation inside the class. Each method or variable in a class may be marked private or public.
P olymorphism Polymorphism is something like  one name, many forms .  Polymorphism manifests itself in Java in the form of  multiple methods having the same name.  In some cases, multiple methods have the same name, but  different formal argument lists( overloaded methods) Example overload.java In other cases, multiple methods have the same name, same  return type, and same formal argument list  (overridden methods) .   Example override.java
Interface Interface is a device or a system that unrelated entities use  to interact.  Remote control is an interface between you and a television .   T he English language is an interface between two people.  Use an interface to define a behavior that can be  implemented by any class. So interface is a collection  of methods that indicate a class has some behaviour  in addition to what it inherits from its superclass.
Interface •  Interface forms a contract between the class and outside world. If the class claims to implement an interface, all methods  defined by that interface must appear in its source code. •  Using interface , you can specify what a class must do,  but not how it does it. •  Interfaces are syntactically similar to classes, but they  lack instance variables, and their methods are declared  without any body  •  Any number of classes can implement an  interface .  also, one class can implement any number of interfaces.
Interface   •  Variables  declared inside of interface declarations  are implicitly public,  final   and  static   •  They must also   be initialized with a constant value   •  All methods are implicitly  public and abstract.   •  Interface methods cannot be marked final, strictfp or native. •  An interface can extend one or more other interfaces. •  An interface cannot implement another interface or class. Example  Callback.java, Client.java
Example  interface Callback { void callback(int param); } Implementing Interfaces To implement an interface, include the  implements  clause  in a class definition,   class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } }
The following interface method declarations won't compile: final void bounce(); // final and abstract can never be used   // together, and abstract is implied static void bounce(); // interfaces define instance methods private void bounce(); // interface methods are always public protected void bounce(); // (same as above)
Declaring Java Classes •  Basic syntax of a Java class: <class_declaration>  ::= <modifier>  class  <name>{ <attribute_declaration>* <constructor_declaration>* <method_declaration>* }
Example: public  class  Vehicle  { private  double  maxLoad; public  void  setMaxLoad(double  value)  { maxLoad  =  value; } }
Declaring Attributes •  Basic syntax of an attribute: <attribute_declaration>  ::= <modifier><type><name>[=<default_value>]; <type>  ::=  byte  |  short  |  int  |  long  |  char float  |  double  |  boolean  |  <class>  
Examples: public  class  Foo  { public  int  x; private  float  y  =  10000.0F; private  String  name  =  &quot;Fred  Flintstone&quot;; }
Declaring Methods •  Basic syntax of a method: <method_declaration>  ::= <modifier><return_type><name>(<parameter>*){ <statement>* }
Examples: public  int  getX()  { return  x; } public  void  setX(int  new_x)  { x  =  new_x; }
Accessing Object Members •  The &quot;dot&quot; notation: <object>.<member> •  This is used to access object members including  attributes and methods  Examples: thing1.setX(47); thing1.x  =  47;  //  only  permissible  if  x  is  public
Example public class Testing{ int i=10; public void a(){ System.out.print(&quot;Value of i is &quot;); } public static void main(String args[]){ Testing t = new Testing(); t.a(); System.out.println(t.i); } }
Declaring Constructors •  Basic syntax of a constructor: <modifier><class_name>(<parameter>*)  { <statement>* } •  Constructors are a special sort of method  that initialise objects.
Examples: public  class  Thing  { private  int  x; public  Thing()  { x  =  47; } public  Thing(int  new_x)  { x  =  new_x; } }
Constructors •  They don't create objects, just initialise them •  They have the same name as the class.  •  If you don't define any constructors, Java will  generate a default no-argument constructor for you.
Constructors •  super(xxx) or this(xxx) is always the first line of  code in a constructor,if not, java will automatically  insert a call to the default no-argument superclass  constructor super() for you.  Example  Derived.java
The Default Constructor •  There is always at least one constructor in every class •  If the writer does not supply any constructors, the default constructor will be present automatically The default constructor takes no arguments  The default constructor has no body  •  Enables you to create object instances with  new Xxx()without having to write a constructor   
Source File Layout •  Basic syntax of a Java source file: <source_file>  ::= [<package_declaration>] <import_declaration>* <class_declaration>+
Example package  shipping.reports.Web; import  shipping.domain.*; import  java.util.List; import  java.io.*; public  class  VehicleCapacityReport  { private  List  vehicles; public  void  generateReport(Writer  output)  {...} }
Packages Packages are nothing more than the way we organize  files into different directories according to their  functionality   Files in one directory (or package) would have different  functionality from those of another directory.   For example, files in java.io package do something  related to I/O but files in java.net package give us the  way to deal with the Network.  Packaging also help us to avoid class name collision.
Packages •  Packages help manage large software systems •  Packages can contain classes and sub-packages •  Basic syntax of the package statement: <package_declaration>  ::= package  <top_pkg_name>[.<sub_pkg_name>].*; Example:  package  shipping.reports.Web; •  Specify the package declaration at the beginning of the  source file
Packages •  Only one package declaration per source file •  If no package is declared, then the class &quot;belongs&quot; to  the default package  •  Package names must be hierarchical and separated by  dot
The import Statement •  Basic syntax of the import statement: <import_declaration> ::= import <pkg_name>[.<sub_pkg_name>]*.<class_name | *>; Examples: import  shipping.domain.*; import  java.util.List; import  java.io.*; •  Precedes all class declarations  •  Tells the compiler where to find classes to use  
Compiling and Running Java files in Package package world;  public class HelloWorld {  public static void main(String[] args) { System.out.println(&quot;Hello World&quot;);  } } When compiling  type C:\ javac world/HelloWorld.java  To run it C:\ java world.HelloWorld
Using the Java API Documentation •  A set of hypertext markup language (HTML) files  provides information about the API  •  One package contains hyperlinks to information on all  of the classes  •  A class document includes the class hierarchy, a  description of the class, a list of member variables, a list  of constructors, and so on   
 

More Related Content

What's hot (20)

PPTX
Introduction to OOP concepts
Ahmed Farag
 
PDF
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
PPT
Lect 1-class and object
Fajar Baskoro
 
PPT
Oops Concept Java
Kamlesh Singh
 
PPT
Java Notes
Abhishek Khune
 
PDF
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
DOCX
java tr.docx
harishkuna4
 
PPTX
Java class,object,method introduction
Sohanur63
 
PPTX
Classes and objects
Anil Kumar
 
PPTX
Java basics
Shivanshu Purwar
 
PPTX
OOPS in Java
Zeeshan Khan
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
oops concept in java | object oriented programming in java
CPD INDIA
 
PDF
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
PDF
Classes and objects in java
Muthukumaran Subramanian
 
PPT
Object Oriented Programming Concepts using Java
Glenn Guden
 
PPTX
Object-oriented programming
Neelesh Shukla
 
DOCX
Core java notes with examples
bindur87
 
PDF
Oop concepts classes_objects
William Olivier
 
Introduction to OOP concepts
Ahmed Farag
 
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
 
Lect 1-class and object
Fajar Baskoro
 
Oops Concept Java
Kamlesh Singh
 
Java Notes
Abhishek Khune
 
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
java tr.docx
harishkuna4
 
Java class,object,method introduction
Sohanur63
 
Classes and objects
Anil Kumar
 
Java basics
Shivanshu Purwar
 
OOPS in Java
Zeeshan Khan
 
Classes, objects in JAVA
Abhilash Nair
 
oops concept in java | object oriented programming in java
CPD INDIA
 
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Classes and objects in java
Muthukumaran Subramanian
 
Object Oriented Programming Concepts using Java
Glenn Guden
 
Object-oriented programming
Neelesh Shukla
 
Core java notes with examples
bindur87
 
Oop concepts classes_objects
William Olivier
 

Viewers also liked (8)

PPT
Md11 gui event handling
Rakesh Madugula
 
PPT
Md121 streams
Rakesh Madugula
 
PPT
A begineers guide of JAVA - Getting Started
Rakesh Madugula
 
PPT
New features and enhancement
Rakesh Madugula
 
PPT
Md08 collection api
Rakesh Madugula
 
PPT
Md13 networking
Rakesh Madugula
 
PPT
Md10 building java gu is
Rakesh Madugula
 
PPT
Md09 multithreading
Rakesh Madugula
 
Md11 gui event handling
Rakesh Madugula
 
Md121 streams
Rakesh Madugula
 
A begineers guide of JAVA - Getting Started
Rakesh Madugula
 
New features and enhancement
Rakesh Madugula
 
Md08 collection api
Rakesh Madugula
 
Md13 networking
Rakesh Madugula
 
Md10 building java gu is
Rakesh Madugula
 
Md09 multithreading
Rakesh Madugula
 
Ad

Similar to Md02 - Getting Started part-2 (20)

PPTX
Introduction to OOP.pptx
ParthaSarathiBehera9
 
PDF
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
Sakthi Durai
 
PDF
CS8392-OOPS-Printed-Notes-All-Units.pdf for students
KaviShetty
 
PPT
java
jent46
 
PPT
Java is an Object-Oriented Language
ale8819
 
PPTX
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
PDF
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
WebStackAcademy
 
PPTX
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
PDF
Java chapter 3 - OOPs concepts
Mukesh Tekwani
 
PDF
Oops concepts
ACCESS Health Digital
 
PPTX
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
PPTX
Note for Java Programming////////////////
MeghaKulkarni27
 
DOCX
Java OOPs Concepts.docx
FredWauyo
 
PPTX
Android Training (Java Review)
Khaled Anaqwa
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
PDF
JAVA-PPT'S.pdf
AnmolVerma363503
 
PDF
A350103
aijbm
 
DOC
Java getstarted
Nobin নবীন
 
Introduction to OOP.pptx
ParthaSarathiBehera9
 
Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of J...
Sakthi Durai
 
CS8392-OOPS-Printed-Notes-All-Units.pdf for students
KaviShetty
 
java
jent46
 
Java is an Object-Oriented Language
ale8819
 
The smartpath information systems java
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
Core Java Programming Language (JSE) : Chapter II - Object Oriented Programming.
WebStackAcademy
 
Object Oriented Programming Tutorial.pptx
ethiouniverse
 
Java chapter 3 - OOPs concepts
Mukesh Tekwani
 
Oops concepts
ACCESS Health Digital
 
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
mohanrajm63
 
Note for Java Programming////////////////
MeghaKulkarni27
 
Java OOPs Concepts.docx
FredWauyo
 
Android Training (Java Review)
Khaled Anaqwa
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
JAVA-PPT'S.pptx
RaazIndia
 
JAVA-PPT'S.pdf
AnmolVerma363503
 
A350103
aijbm
 
Java getstarted
Nobin নবীন
 
Ad

Recently uploaded (20)

PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Dimensions of Societal Planning in Commonism
StefanMz
 

Md02 - Getting Started part-2

  • 1. Module 2 Object-Oriented Programming
  • 2. Objectives • Define modeling concepts: abstraction, encapsulation. • Define class, member, attribute, method, constructor and package • Invoke a method on a particular object. • In a Java program, identify the following: The package statement. The import statements. Classes, methods, and attributes. Constructors. • Use the Java API online documentation
  • 3. Abstraction An essential element of object oriented language is abstraction. Humans manage the complexity through abstraction. For example People do not think of car as a set of tens of thousand of individual parts. They think of it as a well defined object with its own unique behavior. They can ignore the details of how the engine, transmission and braking systems work. Powerful way to manage the abstraction is through the use of hierarchical classifications.
  • 4. From the outside, the car is a single object. Once inside you see that the car consist of several subsystems: steering, brakes, sound system, seat belts ,cellular system and so on. In turn each of these subsystem is made up of more specialized units. For example sound system consist of a radio, a CD player and a tape player. The point is you manage the complexity of car through the use of hierarchical abstraction.
  • 5. Hierarchical abstraction of complex systems can also be applied to computer programs. The data from program can be transformed by abstraction into its component objects. Each object describe its own unique behavior.We can treat these objects as concrete entities that respond to message telling them to do something.
  • 6. Real-world Object s Real-world objects are your dog, your desk, your television set, your bicycle . These real-world objects share two characteristics: They all have state and behavior . For example, dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail).
  • 7. Software objects Software objects are modeled after real-world objects in that they too have state and behavior. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behavior with methods.
  • 8. Classes as Blueprints for Objects • In manufacturing, a blueprint is a description of a device from which many physical devices are constructed. • In software, a class is a description of an object: A class describes the data that each object includes A class describes the behaviors that each object exhibits • In Java, classes support three key features of OOP encapsulation inheritance polymorphism
  • 9. Objects versus Classes In the real world, it's obvious that classes are not themselves the objects they describe: A blueprint of a bicycle is not a bicycle.
  • 10. The Life Cycle of an Object Life cycle of an object involves 1.Creating Objects. 2.Using Objects. 3.Cleaning up unused objects.
  • 11. Creating Objects This statement creates a new Rectangle object from the Rectangle class. Rectangle rect = new Rectangle(); This single statement performs three actions: Declaration : Rectangle rect is a variable declaration that declares to the compiler that the name rect will be used to refer to a Rectangle object. Instantiation : new is a Java operator that creates the new object Initialization : Rectangle() is a call to Rectangle's constructor, which initializes the object.
  • 12. Using Objects Once you've created an object, you probably want to use it for something. You may need information from it, want to change its state, or have it perform some action. Objects give you two ways to do these things: 1.Manipulate or inspect its variables . area = rect.height * rect.width; 2.Call its methods. rect.move(15, 37);
  • 13. Cleaning Up Unused Objects Java allows you to create as many objects as you want and you never have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection. An object is eligible for garbage collection when there are no more references to that object. The Java platform has a garbage collector that periodically frees the memory used by objects that are no longer needed. The garbage collector runs in a low-priority thread
  • 14. Finalization Before an object gets garbage-collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. This process is known as finalization . During finalization, an object may wish to free system resources such as files and sockets or to drop references to other objects so that they in turn become eligible for garbage collection.
  • 15. Key Features of OOPs 1. Inheritanc e 2.Encapsulation 3.P olymorphism
  • 16. Inheritanc e I nheritance is a mechanism that enables one class to inherit all of the behaviour and attributes of another class. For example, mountain bikes, road bikes, are all kinds of bicycles. Mountain bikes, road bikes are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, road bikes. Each subclass inherits state from the superclass. Mountain bikes, road bikes share some states: cadence, speed, and the like. Also, each subclass inherits methods from the superclass. Example inheritance.java
  • 17. Encapsulation • Encapsulation means shielding • The localization of knowledge within a module. • Hides the implementation details of a class. • Makes the code more maintainable
  • 18. Encapsulation in Java In Java the basis of encapsulation is the class. Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. Each method or variable in a class may be marked private or public.
  • 19. P olymorphism Polymorphism is something like one name, many forms . Polymorphism manifests itself in Java in the form of multiple methods having the same name. In some cases, multiple methods have the same name, but different formal argument lists( overloaded methods) Example overload.java In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods) . Example override.java
  • 20. Interface Interface is a device or a system that unrelated entities use to interact. Remote control is an interface between you and a television . T he English language is an interface between two people. Use an interface to define a behavior that can be implemented by any class. So interface is a collection of methods that indicate a class has some behaviour in addition to what it inherits from its superclass.
  • 21. Interface • Interface forms a contract between the class and outside world. If the class claims to implement an interface, all methods defined by that interface must appear in its source code. • Using interface , you can specify what a class must do, but not how it does it. • Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body • Any number of classes can implement an interface . also, one class can implement any number of interfaces.
  • 22. Interface • Variables declared inside of interface declarations are implicitly public, final and static • They must also be initialized with a constant value • All methods are implicitly public and abstract. • Interface methods cannot be marked final, strictfp or native. • An interface can extend one or more other interfaces. • An interface cannot implement another interface or class. Example Callback.java, Client.java
  • 23. Example interface Callback { void callback(int param); } Implementing Interfaces To implement an interface, include the implements clause in a class definition, class Client implements Callback { public void callback(int p) { System.out.println(&quot;callback called with &quot; + p); } }
  • 24. The following interface method declarations won't compile: final void bounce(); // final and abstract can never be used // together, and abstract is implied static void bounce(); // interfaces define instance methods private void bounce(); // interface methods are always public protected void bounce(); // (same as above)
  • 25. Declaring Java Classes • Basic syntax of a Java class: <class_declaration> ::= <modifier> class <name>{ <attribute_declaration>* <constructor_declaration>* <method_declaration>* }
  • 26. Example: public class Vehicle { private double maxLoad; public void setMaxLoad(double value) { maxLoad = value; } }
  • 27. Declaring Attributes • Basic syntax of an attribute: <attribute_declaration> ::= <modifier><type><name>[=<default_value>]; <type> ::= byte | short | int | long | char float | double | boolean | <class>  
  • 28. Examples: public class Foo { public int x; private float y = 10000.0F; private String name = &quot;Fred Flintstone&quot;; }
  • 29. Declaring Methods • Basic syntax of a method: <method_declaration> ::= <modifier><return_type><name>(<parameter>*){ <statement>* }
  • 30. Examples: public int getX() { return x; } public void setX(int new_x) { x = new_x; }
  • 31. Accessing Object Members • The &quot;dot&quot; notation: <object>.<member> • This is used to access object members including attributes and methods Examples: thing1.setX(47); thing1.x = 47; // only permissible if x is public
  • 32. Example public class Testing{ int i=10; public void a(){ System.out.print(&quot;Value of i is &quot;); } public static void main(String args[]){ Testing t = new Testing(); t.a(); System.out.println(t.i); } }
  • 33. Declaring Constructors • Basic syntax of a constructor: <modifier><class_name>(<parameter>*) { <statement>* } • Constructors are a special sort of method that initialise objects.
  • 34. Examples: public class Thing { private int x; public Thing() { x = 47; } public Thing(int new_x) { x = new_x; } }
  • 35. Constructors • They don't create objects, just initialise them • They have the same name as the class. • If you don't define any constructors, Java will generate a default no-argument constructor for you.
  • 36. Constructors • super(xxx) or this(xxx) is always the first line of code in a constructor,if not, java will automatically insert a call to the default no-argument superclass constructor super() for you. Example Derived.java
  • 37. The Default Constructor • There is always at least one constructor in every class • If the writer does not supply any constructors, the default constructor will be present automatically The default constructor takes no arguments The default constructor has no body • Enables you to create object instances with new Xxx()without having to write a constructor  
  • 38. Source File Layout • Basic syntax of a Java source file: <source_file> ::= [<package_declaration>] <import_declaration>* <class_declaration>+
  • 39. Example package shipping.reports.Web; import shipping.domain.*; import java.util.List; import java.io.*; public class VehicleCapacityReport { private List vehicles; public void generateReport(Writer output) {...} }
  • 40. Packages Packages are nothing more than the way we organize files into different directories according to their functionality Files in one directory (or package) would have different functionality from those of another directory. For example, files in java.io package do something related to I/O but files in java.net package give us the way to deal with the Network. Packaging also help us to avoid class name collision.
  • 41. Packages • Packages help manage large software systems • Packages can contain classes and sub-packages • Basic syntax of the package statement: <package_declaration> ::= package <top_pkg_name>[.<sub_pkg_name>].*; Example: package shipping.reports.Web; • Specify the package declaration at the beginning of the source file
  • 42. Packages • Only one package declaration per source file • If no package is declared, then the class &quot;belongs&quot; to the default package • Package names must be hierarchical and separated by dot
  • 43. The import Statement • Basic syntax of the import statement: <import_declaration> ::= import <pkg_name>[.<sub_pkg_name>]*.<class_name | *>; Examples: import shipping.domain.*; import java.util.List; import java.io.*; • Precedes all class declarations • Tells the compiler where to find classes to use  
  • 44. Compiling and Running Java files in Package package world;  public class HelloWorld { public static void main(String[] args) { System.out.println(&quot;Hello World&quot;); } } When compiling type C:\ javac world/HelloWorld.java To run it C:\ java world.HelloWorld
  • 45. Using the Java API Documentation • A set of hypertext markup language (HTML) files provides information about the API • One package contains hyperlinks to information on all of the classes • A class document includes the class hierarchy, a description of the class, a list of member variables, a list of constructors, and so on  
  • 46.