The document discusses different types of constructors in C++ including default, parameterized, copy, and dynamic constructors. It explains that a constructor is a special member function that is called automatically when an object is created to initialize the object's data members. Constructors have the same name as the class and can take arguments to initialize objects with different initial values. The document provides examples of different constructor types.
This document discusses constructors and destructors in C++. It defines constructors as special member functions that initialize object values. Constructors are automatically called when an object is created and can be parameterized to initialize objects with different values. A class can contain multiple constructors. Destructors are used to destroy objects and free allocated memory. They are called automatically when an object goes out of scope.
CONSTRUCTOR AND DESTRUCTOR PPT BASED ON OOP SUBJECT ......FULLY CONCEPT EXPLAINED WITH SAMPLE PROGRAM IN IT .....FOR MORE SLIDES PLEASE FOLLOW ME ..... THANK YOU
The document discusses constructors and destructors in C++. It describes constructor functions as special member functions that initialize object values when an object is created. It covers default constructors, parameterized constructors, copy constructors, and constructor overloading. Destructors are described as special functions that destroy objects and perform cleanup when objects go out of scope. The key characteristics and uses of constructors and destructors are summarized with examples.
The document discusses class objects, constructors, and destructors in C++. It provides an example book class with private data members and public member functions to manipulate the data. Constructors allow objects to initialize their data automatically upon creation without requiring separate calls. Destructors perform cleanup tasks when objects are destroyed. The document also demonstrates how objects are defined and member functions called, and provides examples of classes with constructors and destructors.
The document discusses constructors and destructors in VB.NET. It explains that a constructor is called whenever a new object is created and is used to initialize the object. It has the name "New" and no return type. A destructor, called Finalize in VB.NET, is automatically called when an object is destroyed to perform cleanup tasks like closing files. Examples are provided to demonstrate default and parameterized constructors, as well as destructors.
The document discusses classes, objects, constructors, and other object-oriented programming concepts in C#:
1) A class defines the data and behavior of a type using variables, methods, and events. Objects are instances of classes that have identity, data, and behaviors defined by the class.
2) Constructors initialize objects and are called using the new keyword. Constructors can be overloaded, parameterized, static, or chained to call another constructor.
3) Classes support concepts like inheritance, hiding, overriding, and polymorphism to extend and customize behavior in derived classes. References and values can be passed into methods.
The document discusses different types of constructors in C++ classes:
1. Default constructors are created by the compiler if no constructor is defined, and have no parameters. They initialize member variables.
2. Parameterized constructors allow passing different initialization values to objects, by passing arguments to the constructor.
3. Copy constructors copy the values of data members from one object to another by taking an object as a parameter. They are used to initialize a new object with the same values as an existing object.
The document discusses various types of constructors in C++ including default, parameterized, and copy constructors. It provides examples of how to define each type of constructor and use them to initialize object attributes. It also covers overloaded constructors, constructors with default arguments, and destructors. The key differences between constructors and destructors are that constructors initialize objects while destructors destroy objects, and constructors can take arguments while destructors do not.
- Constructors are special member functions used to initialize objects when they are created. They are automatically called upon object creation and have the same name as the class. Constructors can be default, parameterized, or copy constructors.
- Destructors are also special member functions that perform cleanup actions when an object is destroyed, such as freeing memory. They are called automatically upon object destruction and have the same name as the class preceded by a tilde.
- Examples demonstrate default, parameterized, and copy constructors as well as destructors being defined and called for a class to properly initialize and cleanup objects.
constructor and destructor-object oriented programmingAshita Agrawal
Constructors are special member functions that initialize objects of a class. There are different types of constructors including default, parameterized, and copy constructors. Destructors are used to destroy objects and their name is the same as the class name but preceded by a tilde. Constructors and destructors are important aspects of object oriented programming.
What is a constructor?
Constructor is a method which gets executed automatically when we create or instantiate object of that class having constructor.
More Highlights of Constructor
A single class can have multiple constructors means we can have more than one constructor in a class. It is also called as overloaded constructor.
A benefit of using a constructor is that it guarantees that the object will go through a proper initialization before an object being used means we can pre-initialize some of the class variables with values before an object being used.
A constructor can be called another constructor by using "this" keyword. "this" keyword is the current instance of a class.
Constructors are member functions that initialize objects when they are created. They do not have a return type and are called automatically upon object creation with the same name as the class. There are three types of constructors: default, parameterized, and copy. The default constructor takes no arguments, parameterized constructors allow passing values during object creation, and copy constructors copy the values of one object into a new object. Destructors are special member functions that destroy objects and are declared with a tilde symbol preceding the class name. They are called automatically when program execution finishes or an object is deleted.
Static factory methods have several advantages over constructors for creating object instances, such as returning immutable objects or objects of subclasses. They allow returning an object of any subtype, have named methods instead of anonymous constructors, and can reduce verbosity for parameterized types. Some examples include Boolean.valueOf() and factory methods in the RandomGenerators class.
This document discusses constructors and destructors in C++. It defines a constructor as a special member function with the same name as the class that is used to initialize objects. Constructors are called automatically when objects are created and allow objects to be initialized before use. Constructors cannot be inherited or static and default and copy constructors are generated by the compiler. The document also discusses declaration, default arguments, copy constructors, and the order of constructor invocation.
This document summarizes constructors in Java. Constructors are methods that have the same name as the class and are executed during object creation. Constructors do not have a return type. Constructors are categorized as having no parameters, parameters, or being a default constructor added by the compiler. Constructors without parameters are called with the new keyword, while parameterized constructors pass arguments to the constructor. Default constructors are added by the compiler if no other constructor is defined.
This document provides an overview of key concepts from Lecture 2 of an object-oriented computing course, including:
1) It discusses the basic elements of class definitions such as fields, constructors, and methods. Constructors initialize an object's state while methods implement its behavior.
2) It explains how to define fields, constructors, and methods in a Java class. Constructors set up an object's initial state using fields, while methods can access or modify fields to get/set an object's properties.
3) It uses a ticket machine example to demonstrate class concepts like defining behaviors through methods, passing data via parameters, and distinguishing accessor methods that return data from mutator methods that set an object
A class is a template that defines the form of an object. It specifies both the data and code that will operate on that data. Objects are instances of classes. The data and code that constitute a class are called members or instance variables. A class definition creates a new data type. Objects are created using the new operator, which dynamically allocates memory and returns a reference to the new object. Constructors initialize objects when they are created and can be used to assign initial values to data members. Methods manipulate the data defined by the class and can accept parameters. The garbage collector automatically reclaims memory occupied by objects no longer being used to prevent memory leaks.
The document discusses constructors and the this keyword in Java. It explains that constructors initialize objects and can have parameters. The this keyword refers to the current object instance and can be used to call another constructor from within a constructor. Implicit parameters refer to the current object instance from within member methods and constructors when no explicit reference is provided.
Constructor is a special method in Java that is used to initialize an object. There are two types of constructors: default (no-arg) constructors that have no parameters, and parameterized constructors that allow passing parameters to set object attribute values. Constructors can be overloaded to support different initialization scenarios. They are invoked during object creation to construct and provide initial values for the object's attributes.
Constructor and destructor are special types of methods in object-oriented programming. Constructors are used to initialize objects and are called when an object is created, while destructors are used to destroy objects and are called when an object is deleted or goes out of scope. There are different types of constructors like default, parameterized, and copy constructors. Constructors cannot be inherited or virtual. Destructors are used to clean up resources used by an object and are called automatically when an object is destroyed. The key differences between constructors and destructors are that constructors initialize objects and can have parameters, while destructors destroy objects and have no parameters.
The document discusses classes, objects, and methods in object-oriented programming. It introduces the Dice class as an example, which models the behavior and properties of dice. The Dice class has private member variables to store the number of sides and rolls, and public methods like Roll() and NumSides() to access and manipulate these properties. The document explains concepts like encapsulation, properties, static methods, and the importance of classes and objects in organizing code into reusable components.
A constructor is a special member function that initializes the objects of a class. It has the same name as the class and is invoked automatically whenever a new object is created. Constructors ensure that objects are properly initialized. For example, a constructor for class add that initializes data members m and n to 0 would be automatically called when an add object is declared, initializing m and n without any other code.
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
The document discusses key concepts in Java classes and objects including constructors, method overloading, and static members. Constructors allow objects to be initialized when created and can have different signatures to support multiple initialization options. Method overloading allows multiple methods with the same name but different parameters, while static members like variables and methods exist independently of any object and can be accessed via the class name. The document provides examples demonstrating how to define and use constructors, overloaded methods, and static members when working with classes in Java.
The document discusses various C# concepts including constructors, inheritance, interfaces, collections, fields, and properties. It provides examples of how to use constructors to initialize objects, implement inheritance through deriving classes, define and implement interfaces, use collection classes like ArrayList and List, declare fields to store data in classes, and define properties as a way to encapsulate fields.
The document discusses classes, objects, constructors, and other object-oriented programming concepts in C#:
1) A class defines the data and behavior of a type using variables, methods, and events. Objects are instances of classes that have identity, data, and behaviors defined by the class.
2) Constructors initialize objects and are called using the new keyword. Constructors can be overloaded, parameterized, static, or chained to call another constructor.
3) Classes support concepts like inheritance, hiding, overriding, and polymorphism to extend and customize behavior in derived classes. References and values can be passed into methods.
The document discusses different types of constructors in C++ classes:
1. Default constructors are created by the compiler if no constructor is defined, and have no parameters. They initialize member variables.
2. Parameterized constructors allow passing different initialization values to objects, by passing arguments to the constructor.
3. Copy constructors copy the values of data members from one object to another by taking an object as a parameter. They are used to initialize a new object with the same values as an existing object.
The document discusses various types of constructors in C++ including default, parameterized, and copy constructors. It provides examples of how to define each type of constructor and use them to initialize object attributes. It also covers overloaded constructors, constructors with default arguments, and destructors. The key differences between constructors and destructors are that constructors initialize objects while destructors destroy objects, and constructors can take arguments while destructors do not.
- Constructors are special member functions used to initialize objects when they are created. They are automatically called upon object creation and have the same name as the class. Constructors can be default, parameterized, or copy constructors.
- Destructors are also special member functions that perform cleanup actions when an object is destroyed, such as freeing memory. They are called automatically upon object destruction and have the same name as the class preceded by a tilde.
- Examples demonstrate default, parameterized, and copy constructors as well as destructors being defined and called for a class to properly initialize and cleanup objects.
constructor and destructor-object oriented programmingAshita Agrawal
Constructors are special member functions that initialize objects of a class. There are different types of constructors including default, parameterized, and copy constructors. Destructors are used to destroy objects and their name is the same as the class name but preceded by a tilde. Constructors and destructors are important aspects of object oriented programming.
What is a constructor?
Constructor is a method which gets executed automatically when we create or instantiate object of that class having constructor.
More Highlights of Constructor
A single class can have multiple constructors means we can have more than one constructor in a class. It is also called as overloaded constructor.
A benefit of using a constructor is that it guarantees that the object will go through a proper initialization before an object being used means we can pre-initialize some of the class variables with values before an object being used.
A constructor can be called another constructor by using "this" keyword. "this" keyword is the current instance of a class.
Constructors are member functions that initialize objects when they are created. They do not have a return type and are called automatically upon object creation with the same name as the class. There are three types of constructors: default, parameterized, and copy. The default constructor takes no arguments, parameterized constructors allow passing values during object creation, and copy constructors copy the values of one object into a new object. Destructors are special member functions that destroy objects and are declared with a tilde symbol preceding the class name. They are called automatically when program execution finishes or an object is deleted.
Static factory methods have several advantages over constructors for creating object instances, such as returning immutable objects or objects of subclasses. They allow returning an object of any subtype, have named methods instead of anonymous constructors, and can reduce verbosity for parameterized types. Some examples include Boolean.valueOf() and factory methods in the RandomGenerators class.
This document discusses constructors and destructors in C++. It defines a constructor as a special member function with the same name as the class that is used to initialize objects. Constructors are called automatically when objects are created and allow objects to be initialized before use. Constructors cannot be inherited or static and default and copy constructors are generated by the compiler. The document also discusses declaration, default arguments, copy constructors, and the order of constructor invocation.
This document summarizes constructors in Java. Constructors are methods that have the same name as the class and are executed during object creation. Constructors do not have a return type. Constructors are categorized as having no parameters, parameters, or being a default constructor added by the compiler. Constructors without parameters are called with the new keyword, while parameterized constructors pass arguments to the constructor. Default constructors are added by the compiler if no other constructor is defined.
This document provides an overview of key concepts from Lecture 2 of an object-oriented computing course, including:
1) It discusses the basic elements of class definitions such as fields, constructors, and methods. Constructors initialize an object's state while methods implement its behavior.
2) It explains how to define fields, constructors, and methods in a Java class. Constructors set up an object's initial state using fields, while methods can access or modify fields to get/set an object's properties.
3) It uses a ticket machine example to demonstrate class concepts like defining behaviors through methods, passing data via parameters, and distinguishing accessor methods that return data from mutator methods that set an object
A class is a template that defines the form of an object. It specifies both the data and code that will operate on that data. Objects are instances of classes. The data and code that constitute a class are called members or instance variables. A class definition creates a new data type. Objects are created using the new operator, which dynamically allocates memory and returns a reference to the new object. Constructors initialize objects when they are created and can be used to assign initial values to data members. Methods manipulate the data defined by the class and can accept parameters. The garbage collector automatically reclaims memory occupied by objects no longer being used to prevent memory leaks.
The document discusses constructors and the this keyword in Java. It explains that constructors initialize objects and can have parameters. The this keyword refers to the current object instance and can be used to call another constructor from within a constructor. Implicit parameters refer to the current object instance from within member methods and constructors when no explicit reference is provided.
Constructor is a special method in Java that is used to initialize an object. There are two types of constructors: default (no-arg) constructors that have no parameters, and parameterized constructors that allow passing parameters to set object attribute values. Constructors can be overloaded to support different initialization scenarios. They are invoked during object creation to construct and provide initial values for the object's attributes.
Constructor and destructor are special types of methods in object-oriented programming. Constructors are used to initialize objects and are called when an object is created, while destructors are used to destroy objects and are called when an object is deleted or goes out of scope. There are different types of constructors like default, parameterized, and copy constructors. Constructors cannot be inherited or virtual. Destructors are used to clean up resources used by an object and are called automatically when an object is destroyed. The key differences between constructors and destructors are that constructors initialize objects and can have parameters, while destructors destroy objects and have no parameters.
The document discusses classes, objects, and methods in object-oriented programming. It introduces the Dice class as an example, which models the behavior and properties of dice. The Dice class has private member variables to store the number of sides and rolls, and public methods like Roll() and NumSides() to access and manipulate these properties. The document explains concepts like encapsulation, properties, static methods, and the importance of classes and objects in organizing code into reusable components.
A constructor is a special member function that initializes the objects of a class. It has the same name as the class and is invoked automatically whenever a new object is created. Constructors ensure that objects are properly initialized. For example, a constructor for class add that initializes data members m and n to 0 would be automatically called when an add object is declared, initializing m and n without any other code.
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
The document discusses key concepts in Java classes and objects including constructors, method overloading, and static members. Constructors allow objects to be initialized when created and can have different signatures to support multiple initialization options. Method overloading allows multiple methods with the same name but different parameters, while static members like variables and methods exist independently of any object and can be accessed via the class name. The document provides examples demonstrating how to define and use constructors, overloaded methods, and static members when working with classes in Java.
The document discusses various C# concepts including constructors, inheritance, interfaces, collections, fields, and properties. It provides examples of how to use constructors to initialize objects, implement inheritance through deriving classes, define and implement interfaces, use collection classes like ArrayList and List, declare fields to store data in classes, and define properties as a way to encapsulate fields.
Constructor and Destructor in C++ are special member functions that are automatically called by the compiler.
Constructors initialize a newly created object and are called when the object is created. Destructors destroy objects and release memory and are called when the object goes out of scope. There are different types of constructors like default, parameterized, and copy constructors that allow initializing objects in different ways. Destructors do not have arguments or return values and are declared with a tilde symbol preceding the class name.
OOP stands for Object-Oriented Programming. It involves creating objects that contain both data and methods. Classes act as templates for objects and define their attributes and behaviors. Some advantages of OOP include reusability, organization, and reduced repetition of code. Classes contain fields to store data and methods to perform actions on that data. Objects are instances of classes that inherit all fields and methods. Constructors initialize objects and can set initial field values. Arrays can store multiple objects. Dynamic arrays allow adding elements at runtime. Partial classes allow splitting a class definition across multiple files.
The document provides instructions for two programming assignments:
1. Create a Cylinder class with radius and height variables, a constructor to initialize them, and a volume() method. Also create a CylinderTest class with a main() method that declares a Cylinder array, prompts the user for cylinder properties, and displays the calculated volumes.
2. Create a Date class with month, day, and year variables and a nextDay() method to increment the date. Also create a DateTest class with a main() method that prompts the user for a start date, creates a Date object, and loops 40 times calling nextDay() and displaying the result to test date wrapping.
This document provides an overview of classes in Java. It discusses key concepts like class templates, objects, fields, methods, access modifiers, constructors, static members, and class design best practices. Specifically, it defines a class as a template for objects that encapsulates data and functions, and notes that objects are instances of classes. It also explains how to declare fields and methods, the different access levels for class members, and how to define constructors including overloaded and parameterized constructors.
Software objects consist of state stored in fields and behavior exposed through methods. Objects share state and behavior with real-world objects. A class defines the blueprint for a software object by grouping related fields and methods; individual objects are instances of their class. Inheritance allows subclasses to extend the functionality of the superclass while interfaces define standardized behavior without implementation. Packages organize related classes and interfaces.
A constructor is a special member function that initializes objects of a class. Constructors are automatically called when an object is created. There are different types of constructors like the default constructor, parameterized constructor, copy constructor, and dynamic constructor. A destructor is used to destroy objects and is called automatically when an object goes out of scope.
Constructors are methods that are automatically called when an object is created. They initialize instance fields and perform other initialization tasks. If no constructor is written, Java provides a default constructor that initializes numeric fields to 0, boolean fields to false, and reference variables to null. Constructors can be overloaded to provide different initialization options. Objects can be passed as arguments to methods, with the object's memory address being passed in rather than the object itself.
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Python classes allow for the creation of object-oriented programming in Python. Classes define blueprints for objects with shared attributes and behaviors. Key aspects of classes include defining attributes and methods, constructing objects from classes, inheritance that allows subclasses to extend parent classes, and special methods that enable built-in behaviors. Classes are a fundamental part of Python that enable code reuse and organization.
This document discusses constructors and destructors in C++. It defines constructors as special member functions that initialize object values. Constructors are automatically called when an object is created and can be parameterized to initialize objects with different values. A class can contain multiple constructors. Destructors are used to destroy objects and free allocated memory. They are called automatically when an object goes out of scope.
Python classes allow for the creation of object-oriented programming through defining blueprints for objects with shared attributes and behaviors. Classes are created using the class keyword and contain attributes like variables and methods like functions. Objects are instantiated from classes and can access both class level and instance level attributes. Key concepts covered include inheritance, encapsulation, polymorphism, and special methods.
This document discusses classes and objects in Java. It begins by defining what classes, objects, methods, and instance variables are. It then explains how to declare a class and use it to create objects. It shows how to declare methods and instance variables to define a class's behaviors and attributes. It demonstrates how to call an object's methods to execute tasks. The document also discusses the differences between instance variables and local variables, and how constructors initialize an object's data upon creation. Overall, the document provides an introduction to object-oriented programming concepts in Java like classes, objects, methods, variables, and constructors.
Object Oriented Programming - 5. Class & ObjectAndiNurkholis1
This document provides an overview of object-oriented programming concepts like classes, objects, attributes, and methods in Java. It explains that everything in OOP is associated with classes and objects. A class acts as a blueprint to create objects with attributes and methods. It demonstrates how to define a class, create objects from classes, access and modify attribute values, define static and non-static methods, and call methods on objects. The document also discusses using multiple classes by creating objects of one class and accessing them from another class.
This document discusses classes, methods, objects, constructors and other object-oriented programming concepts in Java. Some key points:
- Classes are templates that define objects, while objects are instances of classes that have state and behavior.
- Methods are collections of code that perform specific tasks and provide reusability. The main() method is important as it is executed first.
- Constructors initialize objects and are automatically called when objects are created. There can be default and parameterized constructors.
- Objects are created using the new keyword and access class members like methods using the dot operator. Arrays can store multiple objects.
- Methods and constructors can be overloaded when they have the same name but different parameters
Multiple Choice Questions on JAVA (object oriented programming) bank 8 -- int...Kuntal Bhowmick
This document contains a bank of multiple choice questions about object oriented programming interfaces. It includes 21 questions about interfaces, each with 4 possible answers, followed by an explanation of the correct answer. The questions cover topics like how interfaces define methods without implementation, how classes implement interfaces, and how interfaces can extend other interfaces.
Multiple Choice Questions on JAVA (object oriented programming) bank 7 -- abs...Kuntal Bhowmick
The document contains a collection of multiple choice questions and answers about abstract classes in object-oriented programming. It includes 14 questions that test understanding of key concepts of abstract classes such as: when the abstract keyword is used, defining abstract methods, preventing instantiation of abstract classes, requiring subclasses to implement abstract methods, and preventing inheritance of classes. Each question is presented on an even page with its answer on the adjacent odd page.
Multiple Choice Questions on JAVA (object oriented programming) bank 6 -- inh...Kuntal Bhowmick
This document contains a 20 question multiple choice quiz about object oriented programming concepts related to inheritance. Each question is presented on an even page with the corresponding answer and explanation on the adjacent odd page. The quiz covers topics like superclass vs subclass, method overriding vs hiding, inheritance terminology in Java, and advantages/disadvantages of inheritance. The document instructs readers to first attempt each question before looking at the solution, and suggests viewing it in single page mode for clarity.
Multiple Choice Questions on JAVA (object oriented programming) bank 5 -- mem...Kuntal Bhowmick
This document contains 18 multiple choice questions about memory management in object-oriented programming. It provides the questions, possible answers, and explanations for the answers. The questions cover topics like garbage collection, heap fragmentation, advantages and disadvantages of garbage collection, the finalize() method, the this keyword, call by value vs call by reference, final variables and methods, static and nested classes.
Multiple Choice Questions on JAVA (object oriented programming) bank 4 -- loopsKuntal Bhowmick
1. The document contains 10 multiple choice questions about loops in object oriented programming.
2. Each question is presented on an even page with the solution provided on the adjacent odd page.
3. The questions cover topics like the while loop condition, do-while loop execution, for loop syntax, and the use of break and continue statements.
Multiple Choice Questions on JAVA (object oriented programming) bank 3 -- cla...Kuntal Bhowmick
This document contains a 17-page MCQ quiz on object-oriented programming concepts like classes, objects, and conditional statements. It includes 18 multiple choice questions about topics such as the difference between classes and objects, access specifiers, method overloading, constructors, and if statements. Each question is presented on an even page with the corresponding explanation and answer on the adjacent odd page. The document instructs readers to first attempt each question themselves before checking the solution.
Multiple Choice Questions on JAVA (object oriented programming) bank 2 -- bas...Kuntal Bhowmick
This document contains a 20-question multiple choice quiz on basic object-oriented programming concepts in Java. Each question is presented on an even page with possible answer options, while the corresponding solution and explanation is given on the adjacent odd page. The quiz covers fundamental topics like data types, access specifiers, inheritance, polymorphism, and more.
Multiple Choice Questions on JAVA (object oriented programming) bank 1 -- int...Kuntal Bhowmick
This document contains 20 multiple choice questions about object-oriented programming concepts. It provides the questions on adjacent even pages and the answers on adjacent odd pages. Some key concepts covered include encapsulation, inheritance, polymorphism, abstraction, and the differences between Java and C++.
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Kuntal Bhowmick
A Hash table is a data structure used for storing and retrieving data very quickly. Insertion of data in the hash table is based on the key value. Hence every entry in the hash table is associated with some key.
HASHING AND HASH FUNCTIONS, HASH TABLE REPRESENTATION, HASH FUNCTION, TYPES OF HASH FUNCTIONS, COLLISION, COLLISION RESOLUTION, CHAINING, OPEN ADDRESSING – LINEAR PROBING, QUADRATIC PROBING, DOUBLE HASHING
introduction to E-commerce, Electronic commerce, EDI, CS802E,
e-commerce ,edi ,electronic data interchange ,traditional commerce ,buyer and seller ,origin of e-commerce ,business process ,impact of e-commerce ,value chain analysis ,company value chain ,case studies on e-commerce ,advantages of e-commerce ,disadvantages of e-commerce
The Bresenham's line algorithm uses integer calculations to draw lines on a raster display. It works by determining which pixel to plot next along the line based on a decision parameter. The parameter is initially calculated based on the line's slope and endpoints, and then updated as the algorithm moves from pixel to pixel. This allows the algorithm to avoid floating point arithmetic for improved efficiency.
- Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. It runs on a variety of platforms such as Windows, Mac OS, and UNIX.
- The Java Virtual Machine (JVM) allows Java code to run on different platforms, as the bytecode is interpreted by the JVM rather than being compiled into platform-specific machine code.
- Some key features of Java include being object-oriented, platform independent, robust, interpreted, and multi-threaded.
This document provides an overview of object-oriented programming concepts in Java including encapsulation, inheritance, polymorphism, and abstraction. It also discusses key Java features like classes, interfaces, access modifiers, and differences between abstract classes and interfaces. Object-oriented principles like encapsulation, inheritance and polymorphism are explained along with examples. Common questions about Java concepts are also addressed at the end.
This document discusses various operating system concepts related to processes and threads. It defines key process terms like process state, process control block, and scheduling queues. It describes the different types of scheduling including long term, short term, and medium term scheduling. It also discusses process states like new, ready, running, waiting, and terminated. Process control blocks are described as storing information about the process state, program counter, CPU registers, scheduling, memory management, I/O status, and accounting. Scheduling queues include the job queue, ready queue, and device queues.
This document provides an overview of networking concepts including definitions of key terms like network, link, node, gateway, transmission media, protocols, error detection, and reliable data transmission protocols. It discusses the layers of the OSI model and responsibilities of each layer. Finally, it covers data link layer protocols, framing, flow control, error control techniques like ARQ, and reliable transmission protocols like stop-and-wait and sliding window protocols.
The document contains summaries of several C programming examples:
1. Programs to calculate the area and circumference of a circle, find simple interest, convert temperatures between Celsius and Fahrenheit, calculate subject marks and percentages, and calculate gross salary.
2. Additional programs demonstrate swapping values with and without a third variable, finding the greatest of three numbers, determining if a year is a leap year, and identifying integers as odd or even, positive or negative.
3. Further programs check if an integer is divisible by 5 and 11, compare two integers for equality, use a switch statement to print days of the week, and perform arithmetic operations using a switch case.
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
The role of the lexical analyzer
Specification of tokens
Finite state machines
From a regular expressions to an NFA
Convert NFA to DFA
Transforming grammars and regular expressions
Transforming automata to grammars
Language for specifying lexical analyzers
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
Data Structures_Linear data structures Linked Lists.pptxRushaliDeshmukh2
Concept of Linear Data Structures, Array as an ADT, Merging of two arrays, Storage
Representation, Linear list – singly linked list implementation, insertion, deletion and searching operations on linear list, circularly linked lists- Operations for Circularly linked lists, doubly linked
list implementation, insertion, deletion and searching operations, applications of linked lists.
Value Stream Mapping Worskshops for Intelligent Continuous SecurityMarc Hornbeek
This presentation provides detailed guidance and tools for conducting Current State and Future State Value Stream Mapping workshops for Intelligent Continuous Security.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
Degree_of_Automation.pdf for Instrumentation and industrial specialistshreyabhosale19
Class notes(week 3) on class objects and methods
1. Page 1 of 31
Class Notes on Class Objects and Methods (Week - 3)
Contents:- Definingaclass,DatafieldsDeclaration,Creating Objects, Accessing Class Members, Constructors, Methods
Overloading, access specifiers, operators, control statements & loops, array, finalize and garbage collection, this
keyword,use of objectsasparameter & methods returning objects, call by value & call by reference, static variables &
methods, garbage collection, nested and inner classes.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of
other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of
blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an
instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are
created.
The following Bicycle class is one possible implementation of a bicycle:
class Bicycle {
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the
previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the
methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete
application; it's just the blueprint for bicycles that might be used in an application. The responsibility of
creating and using new Bicycle objects belongs to some other class in your application.
2. Page 2 of 31
Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:
class BicycleDemo {
public static void main(String[] args) {
// Create two different
// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3
Declaring Member Variables
There are several kinds of variables:
Member variables in a class—these are called fields.
Variables in a method or block of code—these are called local variables.
Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:
1. Zero or more modifiers, such as public or private.
2. The field's type.
3. The field's name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public
keyword identifies these fields as public members, accessible by any object that can access the class.
3. Page 3 of 31
Objects
A typical Java program creates many objects, which as you know, interact by invoking methods. Through these
object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation,
or sending and receiving information over a network. Once an object has completed the work for which it was
created, its resources are recycled for use by other objects.
The following two statements of BicycleDemo class create two separate Bicycle objects.
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
Creating Objects
As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following
statements taken from the BicycleDemo program creates an object and assigns it to a variable:
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
The 2 line creates an object of the Bicycle class.
Each of these statements has three parts (discussed in detail below):
1. Declaration: The code setin bold are all variable declarationsthatassociate avariable name withanobject
type.
2. Instantiation:The new keywordisa Java operatorthat createsthe object.
3. Initialization:The new operatoris followedbyacall to a constructor,whichinitializesthe new object.
Declaring a Variable to Refer to an Object
Previously, you learned that to declare a variable, you write:
type name;
This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable,
this declaration also reserves the proper amount of memory for the variable.
You can also declare a reference variable on its own line. For example:
Point originOne;
If you declare originOne like this, its value will be undetermined until an object is actually created and
assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the
new operator, as described in the next section. You must assign an object to originOne before you use it in
your code. Otherwise, you will get a compiler error.A variable in this state, which currently references no
object, can be illustrated as follows (the variable name, originOne, plus a reference pointing to nothing):
4. Page 4 of 31
Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and returning a reference to that
memory. The new operator also invokes the object constructor.
Note:The phrase "instantiatingaclass"meansthe same thingas "creatingan object."Whenyoucreate an object,you
are creatingan "instance"of a class,therefore "instantiating"aclass.
The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor
provides the name of the class to instantiate.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable
of the appropriate type, like:
Point originOne = new Point(23, 94);
Initializing an Object
Here's the code for the Point class:
class Point {
public int x = 0;
public int y = 0;
//constructor
Point(int a, int b) {
x = a;
y = b;
}
}
This class contains a single constructor. You can recognize a constructor because its declaration uses the same
name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as
declared by the code (int a, int b). The following statement provides 23 and 94 as values for those arguments:
Point originOne = new Point(23, 94);
The result of executing this statement can be illustrated in the next figure:
5. Page 5 of 31
Here's the code for the Rectangle class, which contains four constructors:
class Rectangle {
int width = 0;
int height = 0;
Point origin;
// four constructors
Rectangle() {
origin = new Point(0, 0);
}
Rectangle(Point p) {
origin = p;
}
Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing the area of the rectangle
int getArea() {
return width * height;
}
}
Each constructor lets you provide initial values for the rectangle's size and width, using both primitive and
reference types. If a class has multiple constructors, they must have different signatures. The Java compiler
differentiates the constructors based on the number and the type of the arguments. When the Java compiler
encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point
argument followed by two integer arguments:
Rectangle rectOne = new Rectangle(originOne, 100, 200);
This calls one of Rectangle's constructors that initializes origin to originOne. Also, the constructor sets width to
100 and height to 200. Now there are two references to the same Point object—an object can have multiple
references to it, as shown in the next figure:
6. Page 6 of 31
The following line of code calls the Rectangle constructor that requires two integer arguments, which provide
the initial values for width and height. If you inspect the code within the constructor, you will see that it
creates a new Point object whose x and y values are initialized to 0:
Rectangle rectTwo = new Rectangle(50, 100);
The Rectangle constructor used in the following statement doesn't take any arguments, so it's called a no-
argument constructor:
Rectangle rect = new Rectangle();
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler
automatically provides a no-argument constructor, called the default constructor. This default constructor
calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If
the parent has no constructor (Object does have one), the compiler will reject the program.
Defining Methods
Here is an example of a typical method declaration:
public double calculateAnswer(double wingSpan, int numberOfEngines,
double length, double grossTons) {
//do the calculation here
}
The only required elements of a method declaration are the method's return type, name, a pair of
parentheses, (), and a body between braces, {}.
More generally, method declarations have six components, in order:
1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the method does not
return a value.
3. The method name—the rules for field names apply to method names as well, but the convention is a
little different.
4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data
types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the declaration of local
variables, goes here.
Modifiers, return types, and parameters will be discussed later in this lesson. Exceptions are discussed in a
later lesson.
Definition:Twoof the componentsof amethoddeclarationcomprise the methodsignature—themethod'sname and
the parametertypes.
7. Page 7 of 31
The signature of the method declared above is:
calculateAnswer(double, int, double, double)
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention,
method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase,
followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following
words should be capitalized. Here are some examples:
run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty
Typically, a method has a unique name within its class. However, a method might have the same name as
other methods due to method overloading.
Overloading Methods
The Java programming language supports overloading methods, and Java can distinguish between methods
with different method signatures. This means that methods within a class can have the same name if they
have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled
"Interfaces and Inheritance").
Suppose that you have a class that can use calligraphy to draw various types of data (strings, integers, and so
on) and that contains a method for drawing each data type. It is cumbersome to use a new name for each
method—for example, drawString, drawInteger, drawFloat, and so on. In the Java programming language, you
can use the same name for all the drawing methods but pass a different argument list to each method. Thus,
the data drawing class might declare four methods named draw, each of which has a different parameter list.
public class DataArtist {
...
public void draw(String s) {
...
}
public void draw(int i) {
...
}
public void draw(double f) {
...
}
public void draw(int i, double f) {
...
}
}
8. Page 8 of 31
Overloaded methods are differentiated by the number and the type of the arguments passed into the method.
In the code sample, draw(String s) and draw(int i) are distinct and unique methods because they require
different argument types.
You cannot declare more than one method with the same name and the same number and type of arguments,
because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two
methods with the same signature even if they have a different return type.
Note:Overloadedmethodsshouldbe usedsparingly,astheycan make code much lessreadable.
Constructors
A constructor is a special method that is used to initialize a newly created objectand is called just after the
memory is allocated for the objectIt can be used to initialize the objects ,to required ,or default valuesat the
time of object creationIt is not mandatory for the coder to write a constructor for the class
If no user defined constructor is provided for a class, compiler initializes member variables to its default
values.
numeric data types are set to 0
char data types are set to null character(‘’)
reference variables are set to null
In order to create a Constructor observe the following rules
1. It has the same name as the class
2. It should not return a value not even void
class Demo{
int value1; int value2;
Demo(){
value1 = 10; value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
d1.display();
}
}
9. Page 9 of 31
Step 2) Save , Run & Compile the code. Observe the output.
constructor overloading
Constructor overloading is a technique in Java in which a class can have any number of constructors that differ
in parameter lists. The compiler differentiates these constructors by taking into account the number of
parameters in the list and their type
Examples of valid constructors for class Account are
Account(int a);
Account (int a,int b);
Account (String a,int b);
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
Every class has a default Constructor. Default Constructor for class Demo is Demo(). In case you do not provide
this constructor the compiler creates it for you and initializes the variables to default values. You may choose
to override this default constructor and initialize variables to your desired values .But if you specify a
parametrized constructor like Demo(int a) ,and want to use the default constructor Demo(), it is mandatory
for you to specify it. In other words, in case your Constructor is overridden , and you want to use the default
constructor , its need to be specified.
Access Specifiers
10. Page 10 of 31
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a
class and making this class available only through methods. In this way the chance of making accidental
mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via
so-called access specifiers.
Java offers four access specifiers, listed below in decreasing accessibility:
public
protected
default(nospecifier)
private
We look at these access specifiers in more detail.
public
public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with
Java source code can only contain one public class whose name must also match with the filename. If it exists,
this public class represents the application or the applet, in which case the public keyword is necessary to
enable your Web browser or appletviewer to show the applet. You use public classes, methods, or fields only
if you explicitly want to offer access to these entities and if this access cannot do any harm. An example of a
square determined by the position of its upper-left corner and its size:
public class Square { // public class
public x, y, size; // public instance variables
}
protected
protected methods and fields can only be accessed within the same class to which the methods and fields
belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the
protected access level when it is appropriate for a class's subclasses to have access to the method or field, but
not for unrelated classes.
default (no specifier)
If you do not set access to specific level, then such a class, method, or field will be accessible from inside the
same package to which the class, method, or field belongs, but not from outside this package. This access-level
is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling
classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are
directly available to the Tiling class but not outside the geometry package.
private
private methods and fields can only be accessed within the same class to which the methods and fields
belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So,
the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data
are hidden within the class and accessor methods are provided. An example, in which the position of the
upper-left corner of a square can be set or obtained by accessor methods, but individual coordinates are not
accessible to the user.
11. Page 11 of 31
public class Square { // public class
private double x, y // private (encapsulated) instance variables
public setCorner(int x, int y) { // setting values of private fields
this.x = x;
this.y = y;
}
public getCorner() { // setting values of private fields
return Point(x, y);
}
}
Summary ofAccess Specifiers
The followingtable summarizesthe accesslevelpermittedbyeachspecifier.
Situation public protected default private
Accessible to class
from same package?
yes yes yes no
Accessible to class
from differentpackage?
yes no, unless it is a subclass no no
Note the difference between the default access which is in fact more restricted than the protected access.
Without access specifier (the default choice), methods and variables are accessible only within the class that
defines them and within classes that are part of the same package. They are not visible to subclasses unless
these are in the same package. protected methods and variables are visible to subclasses regardless of which
package they are in.
Java Control Flow Statements
Java Control statements control the order of execution in a java program, based on data values and
conditional logic. There are three main categories of control flow statements;
Selection statements: if, if-else and switch.
Loop statements: while, do-while and for.
Transfer statements: break, continue.
We use control statements when we want to change the default sequential order of execution
SelectionStatements -The IfStatement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the
if block is skipped and execution continues with the rest of the program. You can either have a single
statement or a block of code within an if statement. Note that the conditional expression must be a Boolean
expression.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
Below is an example that demonstrates conditional execution based on if statement condition.
12. Page 12 of 31
public class IfStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b)
System.out.println("a > b");
if (a < b)
System.out.println("b > a");
}
}
Output
b > a
The If-else Statement
The if/else statement is an extension of the if statement. If the statements in the if statement fails, the
statements in the else block are executed. You can either have a single statement or a block of code within if-
else blocks. Note that the conditional expression must be a Boolean expression.
The if-else statement has the following syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20;
if (a > b) {
System.out.println("a > b");
} else {
System.out.println("b > a");
}
}
}
Output
b > a
SwitchCase Statement
The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed
by an expression that equates to a no long integral value. Following the controlling expression is a code block
that contains zero or more labeled cases. Each label must equate to an integer constant and each must be
unique. When the switch statement executes, it compares the value of the controlling expression to the values
13. Page 13 of 31
of each case label. The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block. If none of the case label values match,
then none of the codes within the switch statement code block will be executed. Java includes a default label
to use in cases where there are no matches. We can have a nested switch within a case block of an outer
switch.
Its general form is as follows:
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>
…
case labeln: <statementn>
default: <statement>
} // end switch
When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit
in the middle of the switch statement code block, you must insert a break statement, which causes the
program to continue executing after the current code block.
Below is a java example that demonstrates conditional execution based on nested if else statement condition
to find the greatest of 3 numbers.
public class SwitchCaseStatementDemo {
public static void main(String[] args) {
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Output
c is the greatest
14. Page 14 of 31
IterationStatements -While Statement
The while statement is a looping construct control statement that executes a block of code while a condition is
true. You can either have a single statement or a block of code within the while loop. The loop will never be
executed if the testing expression evaluates to false. The loop condition must be a boolean expression.
The syntax of the while loop is
while (<loop condition>)
<statements>
Below is an example that demonstrates the looping construct namely while loop used to print numbers from 1
to 10.
public class WhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Do-while Loop Statement
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead
of at the beginning. This ensures that the loop will be executed at least once. A do-while loop begins with the
keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and
the test expression completes the do-while loop. When the loop condition becomes false, the loop is
terminated and execution continues with the statement immediately following the loop. You can either have a
single statement or a block of code within the do-while loop.
The syntax of the do-while loop is
15. Page 15 of 31
do
<loop body>
while (<loop condition>);
Below is an example that demonstrates the looping construct namely do-while loop used to print numbers
from 1 to 10.
public class DoWhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println("Printing Numbers from 1 to 10");
do {
System.out.println(count++);
} while (count <= 10);
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Below is an example that creates A Fibonacci sequence controlled by a do-while loop
public class Fibonacci {
public static void main(String args[]) {
System.out.println("Printing Limited set of Fibonacci Sequence");
double fib1 = 0;
double fib2 = 1;
double temp = 0;
System.out.println(fib1);
System.out.println(fib2);
do {
temp = fib1 + fib2;
System.out.println(temp);
fib1 = fib2; //Replace 2nd with first number
fib2 = temp; //Replace temp number with 2nd number
} while (fib2 < 5000);
}
}
Output
Printing Limited set of Fibonacci Sequence
16. Page 16 of 31
0.0
1.0
1.0
2.0
3.0
5.0
8.0
13.0
21.0
34.0
55.0
89.0
144.0
233.0
377.0
610.0
987.0
1597.0
2584.0
4181.0
6765.0
For Loops
The for loop is a looping construct which can execute a set of instructions a specified number of times. It’s a
counter controlled loop.
The syntax of the loop is as follows:
for (<initialization>; <loop condition>; <increment expression>)
<loop body>
The first part of a for statement is a starting initialization, which executes once before the loop begins. The
<initialization> section can also be a comma-separated list of expression statements. The second part of a for
statement is a test expression. As long as the expression is true, the loop will continue. If this expression is
evaluated as false the first time, the loop will never be executed. The third part of the for statement is the
body of the loop. These are the instructions that are repeated each time the program executes the loop. The
final part of the for statement is an increment expression that automatically executes after each repetition of
the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the
loop should continue. All the sections in the for-header are optional. Any one of them can be left empty, but
the two semicolons are mandatory. In particular, leaving out the <loop condition> signifies that the loop
condition is true. The (;;) form of for loop is commonly used to construct an infinite loop.
Below is an example that demonstrates the looping construct namely for loop used to print numbers from 1 to
10.
public class ForLoopDemo {
public static void main(String[] args) {
System.out.println("Printing Numbers from 1 to 10");
17. Page 17 of 31
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
Output
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
Transfer Statements - Continue Statement
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top
of the nearest enclosing loop. You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself.
The syntax of the continue statement is
continue; // the unlabeled form
continue <label>; // the labeled form
You can also provide a loop with a label and then use the label in your continue statement. The label name is
optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.
Below is a program to demonstrate the use of continue statement to print Odd Numbers between 1 to 10.
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i + "t");
}
}
}
Output
Odd Numbers
1
18. Page 18 of 31
3
5
7
9
Break Statement
The break statement transfers control out of the enclosing loop ( for, while, do or switch statement). You use a
break statement when you want to jump immediately to the statement following the enclosing control
structure. You can also provide a loop with a label, and then use the label in your break statement. The label
name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested
loops.
The Syntax for break statement is as shown below;
break; // the unlabeled form
break <label>; // the labeled form
Below is a program to demonstrate the use of break statement to print numbers Numbers 1 to 10.
public class BreakExample {
public static void main(String[] args) {
System.out.println("Numbers 1 - 10");
for (int i = 1;; ++i) {
if (i == 11)
break;
// Rest of loop body skipped when i is even
System.out.println(i + "t");
}
}
}
Output
Numbers 1 – 10
1
2
3
4
5
6
7
8
9
10
finalize method
finalize method in java is a special method much like main method in java. finalize() is called before Garbage
collector reclaim the Object, its last chance for any object to perform cleanup activity i.e. releasing any system
resources held, closing connection if open etc. Main issue with finalize method in java is its not guaranteed by
19. Page 19 of 31
JLS that it will be called by Garbage collector or exactly when it will be called, for example an object may wait
indefinitely after becoming eligible for garbage collection and before its finalize() method gets called. similarly
even after finalize gets called its not guaranteed it will be immediately collected. Because of above reason it
make no sense to use finalize method for releasing critical resources or perform any time critical activity inside
finalize. It may work in development in one JVM but may not work in other JVM. In this java tutorial we will
see some important points about finalize method in Java, How to use finalize method, what to do and what
not to do inside finalize in Java.
Garbage Collection
The Java virtual machine's heap stores all objects created by a running Java application. Objects are created by
the new, newarray, anewarray, and multianewarray instructions, but never freed explicitly by the code.
Garbage collection is the process of automatically freeing objects that are no longer referenced by the
program.
This chapter does not describe an official Java garbage-collected heap, because none exists. As mentioned in
earlier chapters, the Java virtual machine specification does not require any particular garbage collection
technique. It doesn't even require garbage collection at all. But until infinite memory is invented, most Java
virtual machine implementations will likely come with garbage-collected heaps. This chapter describes various
garbage collection techniques and explains how garbage collection works in Java virtual machines.
Accompanying this chapter on the CD-ROM is an applet that interactively illustrates the material presented in
the chapter. The applet, named Heap of Fish, simulates a garbage-collected heap in a Java virtual machine.
The simulation--which demonstrates a compacting, mark-and-sweep collector--allows you to interact with the
heap as if you were a Java program: you can allocate objects and assign references to variables. The simulation
also allows you to interact with the heap as if you were the Java virtual machine: you can drive the processes
of garbage collection and heap compaction. At the end of this chapter, you will find a description of this applet
and instructions on how to use it.
Why Garbage Collection?
The name "garbage collection" implies that objects no longer needed by the program are "garbage" and can
be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When an object is
no longer referenced by the program, the heap space it occupies can be recycled so that the space is made
available for subsequent new objects. The garbage collector must somehow determine which objects are no
longer referenced by the program and make available the heap space occupied by such unreferenced objects.
In the process of freeing unreferenced objects, the garbage collector must run any finalizers of objects being
freed.
In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap
fragmentation occurs through the course of normal program execution. New objects are allocated, and
unreferenced objects are freed such that free portions of heap memory are left in between portions occupied
by live objects. Requests to allocate new objects may have to be filled by extending the size of the heap even
though there is enough total unused space in the existing heap. This will happen if there is not enough
contiguous free heap space available into which the new object will fit. On a virtual memory system, the extra
paging (or swapping) required to service an ever growing heap can degrade the performance of the executing
program. On an embedded system with low memory, fragmentation could cause the virtual machine to "run
out of memory" unnecessarily.
20. Page 20 of 31
Garbage collection relieves you from the burden of freeing allocated memory. Knowing when to explicitly free
allocated memory can be very tricky. Giving this job to the Java virtual machine has several advantages. First,
it can make you more productive. When programming in non-garbage-collected languages you can spend
many late hours (or days or weeks) chasing down an elusive memory problem. When programming in Java you
can use that time more advantageously by getting ahead of schedule or simply going home to have a life.
A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an
important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash
the Java virtual machine by incorrectly freeing memory.
A potential disadvantage of a garbage-collected heap is that it adds an overhead that can affect program
performance. The Java virtual machine has to keep track of which objects are being referenced by the
executing program, and finalize and free unreferenced objects on the fly. This activity will likely require more
CPU time than would have been required if the program explicitly freed unnecessary memory. In addition,
programmers in a garbage-collected environment have less control over the scheduling of CPU time devoted
to freeing objects that are no longer needed.
this keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this
keyword. this can be used inside any method to refer to the current object. That is, this is always a reference
to the object on which the method was invoked. You can use this anywhere a reference to an object of the
current class' type is permitted.
To better understand what this refers to, consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking
object. While it is redundant in this case, this is useful in other contexts, one of which is explained in the next
section.
Instance Variable Hiding
As you know, it is illegal in Java to declare two local variables with the same name inside the same or enclosing
scopes. Interestingly, you can have local variables, including formal parameters to methods, which overlap with
the names of the class' instance variables. However, when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
This is why width, height, and depth were not used as the names of the parameters to the Box( ) constructor
inside the Box class. If they had been, then width would have referred to the formal parameter, hiding the
instance variable width. While it is usually easier to simply use different names, there is another way around
this situation. Because this lets you refer directly to the object, you can use it to resolve any name space
collisions that might occur between instance variables and local variables. For example, here is another version
of Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance
variables by the same name:
21. Page 21 of 31
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
A word of caution: The use of this in such a context can sometimes be confusing, and some programmers are
careful not to use local variables and formal parameter names that hide instance variables. Of course, other
programmers believe the contrary—that it is a good convention to use the same names for clarity, and use
this to overcome the instance variable hiding. It is a matter of taste which approach you adopt.
Although this is of no significant value in the examples just shown, it is very useful in certain situations.
This is an extract from the book: Java 2 - The Complete Reference by Herbert Schildt.
Using Objects as Parameters
So far we have only been using simple types as parameters to methods. However, it is both correct and
common to pass objects to methods. For example, consider the following short program:
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
As you can see, the equals( ) method inside Test compares two objects for equality and returns the result. That
is, it compares the invoking object with the one that it is passed. If they contain the same values, then the
method returns true. Otherwise, it returns false. Notice that the parameter o in equals( ) specifies Test as its
22. Page 22 of 31
type. Although Test is a class type created by the program, it is used in just the same way as Java’s built-in
types. One of the most common uses of object parameters involves constructors. Frequently you will want to
construct a new object so that it is initially the same as some existing object. To do this, you must define a
constructor that takes an object of its class as a parameter. For example, the following version of Box allows
one object to initialize another:
// Here, Box allows one object to initialize another.
class Box {
double width;
double height;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
23. Page 23 of 31
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
As you will see when you begin to create your own classes, providing many forms of constructor methods is
usually required to allow objects to be constructed in a convenient and efficient manner.
Can a java methodreturn an object? Why constructors don’t have a returntype?
Absolutely. Make sure the method is labeled as returning an object
i.e
public Object objectMethod(...){
...
return (theObject);
}
Constructors don't have a return type because they simply "construct" an object. In that sense, they are
already returning an object. Constructors implicitly returns an object, they don’t have any return type not
even void.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call
by value. The changes being done in the called method, is not affected in the calling method.
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3.
4. void change(int data){
5. data=data+100;//changes will be in the local variable only
6. }
7.
8.
9. public static void main(String args[]){
10. Operation op=new Operation();
11.
12. System.out.println("before change "+op.data);
13. op.change(500);
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
afterchange 50
24. Page 24 of 31
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the called method. If we pass
object in place of any primitive value, original value will be changed. In this example we are passing
object as a value. Let's take a simple example:
1. class Operation2{
2. int data=50;
3.
4. void change(Operation op){
5. op.data=op.data+100;//changes will be in the instance variable
6. }
7.
8.
9. public static void main(String args[]){
10. Operation2 op=new Operation2();
11.
12. System.out.println("before change "+op.data);
13. op.change(op);//passing object
14. System.out.println("after change "+op.data);
15.
16. }
17. }
Output:before change 50
afterchange 150
Modifiers:final and static
A number of modifier keywords can be placed in declarations of methods and variables, and sometimes in
declarations of classes, to provide extra information or restriction on the methods or variables. Here we shall
only discuss the final and static keywords.
The final Modifier
The static Modifier
The Geometrical ShapesExample
The final Modifier
The final modifier keyword makes that the programmer cannot change the value anymore. The actual
meaning depends on whether it is applied to a class, a variable, or a method. We look at these three cases in
more detail.
final Classes
A final class cannothave subclasses.Anexample:
public final class MathConstants {
...
}
This skeleton defines a class called MathConstants that is publicly accessible but cannot be subclassed.
final Variables
A final variable cannot be changed once it is initialized, In the above class of mathematical constants you can
for example define a numerical approximation of pi by
public final static double PI = 3.141592654;
25. Page 25 of 31
It is a convention, but not obligatory, to capitalize the name of a final object.
final Methods
A final method cannot be overridden by subclasses. There are two reasons for introducing such a method:
1. Disallowing subclasses to change the meaning of the method;
2. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
In the class of mathematical constants you could define a final method to generate a random constant.
public final static randomNumber() {
...
}
The static Modifier
A variable or method that is shared by all instances of a class is called a class variable or class method. You
recognize such a variable in Java by the static keyword in the declaration. A class variable will instantiate only
one copy of the variable for the whole class instead of a separate copy for each instance of a class. A class
variable belongs to a class, not to an instance of the class.
You can refer to a class variable either through an instance of the class (like a normal instance variable) or
through the full class name of the form classname.variable.
A class method can be referred to through an instance of the class (like a normal method) or through the full
class name of the form classname.method. In fact, a class is an object of the special class Class, so this naming
system is consistent.
You can look at the examples above for how to use class variables and class methods. You can also look at the
example worked out below.
The Geometrical Shapes Example
We shall give an example of the Shape class with the subclasses Circle and Square. In this example you can
practice your knowledge of modifiers and access specifiers.
MathConstants.java
A class for mathematical constants that cannot be subclassed and contains the mathematical constant pi.
public final class MathConstants {
public final static double PI = 3.141592654; // constant pi
}
ShapeCounter.java
A class for counting the number of geometrical objects that cannot be subclassed and does not allow direct
access to the variable that holds in fact the number of shapes; instead, accessor methods are provided to
classes in the same package to which this class belongs.
26. Page 26 of 31
public final class ShapesCounter {
private static int shapesCount = 0; // total number of geometrical objects
private static final int maxCounter = 1000; // maximum number of objects
protected static int shapesCount() {
return shapesCount;
}
protected static void incrementShapesCount() {
shapesCount++;
}
protected static void decrementShapesCount() {
shapesCount--;
}
}
Shape.java
A class defining common aspects of shapes such as the coordinates of the distinguished point of the shape.
public class Shape {
protected double x, y; // position of geometrical object
}
Circle.java
A class for a circular shape with limited radius, a method to rest the maximal size, and methods to compute
the area and the circumference of the circle.
public class Circle extends Shape {
protected double r; // radius
private static double maxSize = 100; // maximal radius
Circle(double x, double y, double r) {
super.x = x;
super.y = y;
this.r = r;
ShapesCounter.incrementShapesCount();
}
public static void setMaxSize(double size) {
maxSize = size;
}
public double area() {
return MathConstants.PI * r * r;
}
public double circumference() {
return 2 * MathConstants.PI * r;
}
}
Square.java
A class for a square shape with methods to compute the area and the circumference of the square.
public class Square extends Shape {
protected double size; // radius
private static double maxSize = 100; // maximal size
Square(double x, double y, double size) {
27. Page 27 of 31
super.x = x;
super.y = y;
this.size = size;
ShapesCounter.incrementShapesCount();
}
public static void setMaxSize(double size) {
maxSize = size;
}
public double area() {
return size * size;
}
public double circumference() {
return 4 * size;
}
}
NestedClasses
The Java programming language allows you to define a class within another class. Such a class is called a
nested class and is illustrated here:
class OuterClass {
...
class NestedClass {
...
}
}
Terminology:Nestedclassesare dividedintotwocategories:staticandnon-static.Nestedclassesthatare declared
static are simplycalled staticnested classes.Non-staticnestedclassesare called innerclasses.
class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other
members of the enclosing class, even if they are declared private. Static nested classes do not have access to
other members of the enclosing class. As a member of the OuterClass, a nested class can be declared private,
public, protected, or package private. (Recall that outer classes can only be declared public or package private.)
Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
28. Page 28 of 31
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class
and keep the two together. Nesting such "helper classes" makes their package more streamlined.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A
that would otherwise be declared private. By hiding class B within class A, A's members can be declared private
and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable code—Nesting small classes within top-level classes places the code closer to
where it is used.
Static NestedClasses
As with class methods and variables, a static nested class is associated with its outer class. And like static class
methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing
class — it can use them only through an object reference.
Note:A static nestedclassinteractswiththe instance membersof itsouterclass(andotherclasses) justlike anyother
top-level class.Ineffect,astaticnestedclassisbehaviorallyatop-level classthathasbeennestedinanothertop-level
classfor packagingconvenience.
Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Inner Classes
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and
has direct access to that object's methods and fields. Also, because an inner class is associated with an
instance, it cannot define any static members itself.
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following
classes:
class OuterClass {
...
class InnerClass {
...
}
}
29. Page 29 of 31
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods
and fields of its enclosing instance. The next figure illustrates this idea.
An Instance of InnerClass Exists Within an Instance of OuterClass
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the
outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Additionally, there are two special kinds of inner classes: local classes and anonymous classes (also called
anonymous inner classes). Both of these will be discussed briefly in the next section.
Inner Class Example
To see an inner class in use, let's first consider an array. In the following example, we will create an array, fill it
with integer values and then output only values of even indices of the array in ascending order.
The DataStructure class below consists of:
The DataStructure outer class, which includes methods to add an integer onto the array and print out values of
even indices of the array.
The InnerEvenIterator innerclass,whichissimilarto a standard Java iterator. Iterators are used to step through a
data structure and typicallyhave methodstotestforthe last element, retrieve the current element, and move
to the next element.
A main method that instantiates a DataStructure object (ds) and uses it to fill the arrayOfInts array with integer
values (0, 1, 2, 3, etc.), then calls a printEven method to print out values of even indices of arrayOfInts.
public class DataStructure {
// create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
public void printEven() {
// print out values of even indices of the array
InnerEvenIterator iterator = this.new InnerEvenIterator();
30. Page 30 of 31
while (iterator.hasNext()) {
System.out.println(iterator.getNext() + " ");
}
}
// inner class implements the Iterator pattern
private class InnerEvenIterator {
// start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
// check if a current element is the last in the array
return (next <= SIZE - 1);
}
public int getNext() {
// record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
public static void main(String s[]) {
// fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
}
}
The output is:
0 2 4 6 8 10 12 14
Note that the InnerEvenIterator class refers directly to the arrayOfInts instance variable of the DataStructure object.
Inner classes can be used to implement helper classes like the one shown in the example above. If you plan on
handling user-interface events, you will need to know how to use inner classes because the event-handling
mechanism makes extensive use of them.
Local and Anonymous Inner Classes
There are two additional types of inner classes. You can declare an inner class within the body of a method.
Such a class is known as a local inner class. You can also declare an inner class within the body of a method
without naming it. These classes are known as anonymous inner classes. You will encounter such classes in
advanced Java programming.
Modifiers
You can use the same modifiers for inner classes that you use for other members of the outer class. For
example, you can use the access specifiers — private, public, and protected — to restrict access to inner
classes, just as you do to other class members.
Summary ofNested Classes
31. Page 31 of 31
A class defined within another class is called a nested class. Like other members of a class, a nested class can
be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can
exist only within an instance of its enclosing class and has access to its enclosing class's members even if they
are declared private.
The following table shows the types of nested classes:
Types of Nested Classes
Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes