This document provides an introduction to object-oriented programming concepts. It discusses breaking programs down into objects rather than procedures, with each object having descriptive data as attributes and associated actions as methods. It provides an example class definition for a Person object, with attributes like age and methods like saying one's age. The document also covers other key concepts like instantiating objects, calling methods, and defining a default constructor.
This document provides an overview of key concepts in Android development including data types, classes and objects, methods, conditional statements, and intents. It explains that data types in Android are the same as in Java, including primitive types like int and double, and non-primitive types like String. Classes are blueprints that define objects with attributes and methods, and an object is an instance of a class. Methods are blocks of code that perform tasks. Conditional statements like if/else execute code based on conditions. Intents allow activities to communicate by passing messages and data between each other to start new activities or perform actions. Explicit intents specify a target component while implicit intents declare a general action.
Object-Oriented Programming (OOP) is a programming technique that treats data and functions as objects. OOP uses classes to define objects that contain properties and methods. Classes act as blueprints for objects. Objects are instances of classes that inherit properties and methods from their class. Key elements of OOP include classes, objects, properties, methods, inheritance, and interfaces.
This document provides an introduction to object-oriented programming concepts in Java including objects, classes, inheritance, polymorphism, and more. It defines key terms like class, object, state, behavior, identity. It also discusses the differences between objects and classes and provides examples of declaring classes and creating objects in Java. Methods, constructors, and initialization of objects are explained. Inheritance, method overriding, and polymorphism are defined along with examples.
This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation and abstraction. It begins by describing the objectives of learning OOP which are to describe objects and classes, define classes, construct objects using constructors, access object members using dot notation, and apply abstraction and encapsulation. It then compares procedural and object-oriented programming, noting that OOP involves programming using objects defined by classes. Key concepts covered include an object's state consisting of data fields and behavior defined by methods. The document demonstrates defining classes, creating objects, accessing object members, and using private data fields for encapsulation.
The document discusses a lecture on object-oriented programming. It covers key topics like classes, objects, fields, methods, constructors, and creating objects from classes. It provides examples of how to define classes with fields, methods, and constructors. It also explains how to compile and run a simple Java program with a main method.
This document discusses JavaScript objects and the Document Object Model (DOM) in JavaScript. It covers:
1. The three ways to create objects in JavaScript - using object literals, the Object constructor, and object constructors. Examples are provided.
2. The document object which represents the HTML document and allows dynamic content to be added to web pages. Properties and methods of the document object are mentioned.
3. An overview of selecting, traversing, manipulating DOM elements using JavaScript. Methods like getElementById(), getElementsByName(), and querySelector() for selection and appendChild(), textContent for manipulation are discussed.
This ppt gives information about:
1. OOPs Theory
2. Defining a Class
3. Creating an Object
4. The $this Attribute
5. Creating Constructors
6. Creating Destructors
This document provides an overview of key concepts in Android development including data types, classes and objects, methods, conditional statements, and intents. It explains that data types in Android are the same as in Java, including primitive types like int and double, and non-primitive types like String. Classes are blueprints that define objects with attributes and methods, and an object is an instance of a class. Methods are blocks of code that perform tasks. Conditional statements like if/else execute code based on conditions. Intents allow activities to communicate by passing messages and data between each other to start new activities or perform actions. Explicit intents specify a target component while implicit intents declare a general action.
Object-Oriented Programming (OOP) is a programming technique that treats data and functions as objects. OOP uses classes to define objects that contain properties and methods. Classes act as blueprints for objects. Objects are instances of classes that inherit properties and methods from their class. Key elements of OOP include classes, objects, properties, methods, inheritance, and interfaces.
This document provides an introduction to object-oriented programming concepts in Java including objects, classes, inheritance, polymorphism, and more. It defines key terms like class, object, state, behavior, identity. It also discusses the differences between objects and classes and provides examples of declaring classes and creating objects in Java. Methods, constructors, and initialization of objects are explained. Inheritance, method overriding, and polymorphism are defined along with examples.
This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation and abstraction. It begins by describing the objectives of learning OOP which are to describe objects and classes, define classes, construct objects using constructors, access object members using dot notation, and apply abstraction and encapsulation. It then compares procedural and object-oriented programming, noting that OOP involves programming using objects defined by classes. Key concepts covered include an object's state consisting of data fields and behavior defined by methods. The document demonstrates defining classes, creating objects, accessing object members, and using private data fields for encapsulation.
The document discusses a lecture on object-oriented programming. It covers key topics like classes, objects, fields, methods, constructors, and creating objects from classes. It provides examples of how to define classes with fields, methods, and constructors. It also explains how to compile and run a simple Java program with a main method.
This document discusses JavaScript objects and the Document Object Model (DOM) in JavaScript. It covers:
1. The three ways to create objects in JavaScript - using object literals, the Object constructor, and object constructors. Examples are provided.
2. The document object which represents the HTML document and allows dynamic content to be added to web pages. Properties and methods of the document object are mentioned.
3. An overview of selecting, traversing, manipulating DOM elements using JavaScript. Methods like getElementById(), getElementsByName(), and querySelector() for selection and appendChild(), textContent for manipulation are discussed.
This ppt gives information about:
1. OOPs Theory
2. Defining a Class
3. Creating an Object
4. The $this Attribute
5. Creating Constructors
6. Creating Destructors
Class is a blueprint for creating objects that share common attributes and behaviors. A class defines the data and methods that describe the object. Classes in Java can contain data members, methods, constructors, nested classes, and interfaces. Objects are instances of classes that occupy memory at runtime and can access class members like variables and methods. Constructors initialize an object when it is created and have the same name as the class. The this keyword refers to the current object in a method or constructor. Command line arguments can be passed to a program as strings and accessed via the args parameter in the main method.
This class is abstract but it does not provide implementation of abstract method print(). An abstract class must be subclassed and the abstract methods must be implemented in the subclass. We cannot create an object of an abstract class directly, it has to be through its concrete subclass.
The document provides an overview of lecture 03 on objects and classes in Java, including reviewing basic concepts, declaring and using classes, implementing inheritance, and discussing abstract classes and interfaces. It also includes examples of declaring classes, using constructors and methods, and implementing inheritance and polymorphism. The lecture aims to help students understand object-oriented concepts in Java like classes, objects, inheritance and polymorphism.
This document provides an overview of object-oriented programming concepts in Java including classes, objects, attributes, and methods. It discusses how classes define templates for objects and how objects are instances of classes. Examples are given of declaring a class for a car with attributes like make and speed, and methods like accelerate and turn. The document also covers creating objects from classes in code, and accessing object attributes and methods. Finally, it briefly introduces some standard Java classes like Math that are commonly used.
C++ppt. Classs and object, class and objectsecondakay
1. Classes are blueprints that define objects with attributes (data members) and behaviors (member functions). Objects are instantiated from classes.
2. The Time class implements a time abstract data type with data members for hours, minutes, seconds and member functions to set time and print time in different formats.
3. Classes allow for encapsulation of data and functions, information hiding of implementation details, and software reusability through class libraries.
This document provides information about a CS 213 object oriented programming course in Java. It lists the instructors, lecture times and groups, assessment model, and course outline. The outline covers an overview of Java, basic syntax including classes, objects, and methods, variables, operators, loops, strings, arrays, exceptions, inheritance, polymorphism, and more. It also includes documentation on Java identifiers, keywords, comments, modifiers, and variables.
C# is an object-oriented programming language created by Microsoft. It was created by a team led by Anders Hejlsberg with the goal of combining the best aspects of existing languages and improving upon them. C# code is compiled into an intermediate language called IL, which is then executed by the Common Language Runtime (CLR). Key concepts of object-oriented programming in C# include classes, objects, abstraction, encapsulation, polymorphism, and inheritance. Classes define the attributes and behaviors of objects, and objects are instances of classes.
C# is an object-oriented programming language created by Microsoft that can be used to create a variety of applications. The key steps in executing a C# program are compilation, where source code is converted to bytecode, and execution, where the bytecode is converted to machine code and run. C# supports important object-oriented concepts like classes, objects, inheritance, polymorphism, abstraction and encapsulation. Classes define the attributes and behaviors of objects, and objects are instantiated from classes. Constructors initialize new objects.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
This document provides an introduction to Objective-C, including:
- Objective-C is a programming language used by Apple for iOS and Mac apps that is a superset of C and adds object-oriented capabilities.
- The language consists of objects, classes, methods, and messages that allow objects to communicate with each other.
- Keywords like @interface, @implementation, and @protocol are used to define classes, categories, and protocols.
- The document discusses features like properties, memory management, and differences between instance and class methods.
This document summarizes a presentation on JavaScript essentials for Java developers. It discusses JavaScript object literals, core objects like Array and Date, JSON, and JavaScript classes. Object literals allow creating objects without classes by using this and properties/methods. Core objects like Array, Date, Math and String are explored. JSON is introduced as a lightweight data interchange format. JavaScript classes are explained using the constructor function pattern and prototype properties to add methods to all objects.
This document discusses object-oriented programming concepts in Objective-C such as classes, inheritance, polymorphism, and exceptions. It covers creating interface and implementation files, using properties and methods, inheritance hierarchies with subclasses, overriding methods, abstract classes, polymorphism through dynamic binding, and exceptions. Key topics include creating .h and .m files to define a class, using self to reference the current object, returning objects from methods, and extending classes through inheritance while allowing method overriding.
The document discusses various topics in Objective-C including variables, data types, categories, protocols, and composite objects. It provides code examples to illustrate initializing objects, variable scope, enumerated data types, typedefs, data type conversion, categories, class extensions, protocols, delegates, and composite objects in Objective-C and compares some of these concepts to Java.
This document provides an overview of test automation using Selenium. It discusses reasons to automate testing such as supporting regression testing and finding defects missed by manual testing. It also discusses when not to automate, such as when an application's behavior is unstable. The document then covers the Selenium framework, its components like Selenium IDE and WebDriver, and languages it supports like Java. It also discusses concepts in object-oriented programming relevant to test automation like classes, objects, inheritance and more.
This document discusses classes and objects in Python. It defines what a class and object are, how to create classes and objects in Python, and provides an example Employee class with two employee objects. A class defines the blueprint for an object, containing attributes and methods. An object is an instance of a class. To create a class in Python, the class keyword is used followed by the class name and contents in a suite. Objects are created by calling the class and passing arguments to its __init__ method. Methods can then be accessed using dot notation on the object.
This document provides an overview of object oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism and more. It also outlines the syllabus for a course on OOP with Java, covering topics like arrays, strings, vectors, exception handling, GUI programming and more. Finally, it provides some examples of basic Java code.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Design and optimization of ion propulsion dronebjmsejournal
Electric propulsion technology is widely used in many kinds of vehicles in recent years, and aircrafts are no exception. Technically, UAVs are electrically propelled but tend to produce a significant amount of noise and vibrations. Ion propulsion technology for drones is a potential solution to this problem. Ion propulsion technology is proven to be feasible in the earth’s atmosphere. The study presented in this article shows the design of EHD thrusters and power supply for ion propulsion drones along with performance optimization of high-voltage power supply for endurance in earth’s atmosphere.
Class is a blueprint for creating objects that share common attributes and behaviors. A class defines the data and methods that describe the object. Classes in Java can contain data members, methods, constructors, nested classes, and interfaces. Objects are instances of classes that occupy memory at runtime and can access class members like variables and methods. Constructors initialize an object when it is created and have the same name as the class. The this keyword refers to the current object in a method or constructor. Command line arguments can be passed to a program as strings and accessed via the args parameter in the main method.
This class is abstract but it does not provide implementation of abstract method print(). An abstract class must be subclassed and the abstract methods must be implemented in the subclass. We cannot create an object of an abstract class directly, it has to be through its concrete subclass.
The document provides an overview of lecture 03 on objects and classes in Java, including reviewing basic concepts, declaring and using classes, implementing inheritance, and discussing abstract classes and interfaces. It also includes examples of declaring classes, using constructors and methods, and implementing inheritance and polymorphism. The lecture aims to help students understand object-oriented concepts in Java like classes, objects, inheritance and polymorphism.
This document provides an overview of object-oriented programming concepts in Java including classes, objects, attributes, and methods. It discusses how classes define templates for objects and how objects are instances of classes. Examples are given of declaring a class for a car with attributes like make and speed, and methods like accelerate and turn. The document also covers creating objects from classes in code, and accessing object attributes and methods. Finally, it briefly introduces some standard Java classes like Math that are commonly used.
C++ppt. Classs and object, class and objectsecondakay
1. Classes are blueprints that define objects with attributes (data members) and behaviors (member functions). Objects are instantiated from classes.
2. The Time class implements a time abstract data type with data members for hours, minutes, seconds and member functions to set time and print time in different formats.
3. Classes allow for encapsulation of data and functions, information hiding of implementation details, and software reusability through class libraries.
This document provides information about a CS 213 object oriented programming course in Java. It lists the instructors, lecture times and groups, assessment model, and course outline. The outline covers an overview of Java, basic syntax including classes, objects, and methods, variables, operators, loops, strings, arrays, exceptions, inheritance, polymorphism, and more. It also includes documentation on Java identifiers, keywords, comments, modifiers, and variables.
C# is an object-oriented programming language created by Microsoft. It was created by a team led by Anders Hejlsberg with the goal of combining the best aspects of existing languages and improving upon them. C# code is compiled into an intermediate language called IL, which is then executed by the Common Language Runtime (CLR). Key concepts of object-oriented programming in C# include classes, objects, abstraction, encapsulation, polymorphism, and inheritance. Classes define the attributes and behaviors of objects, and objects are instances of classes.
C# is an object-oriented programming language created by Microsoft that can be used to create a variety of applications. The key steps in executing a C# program are compilation, where source code is converted to bytecode, and execution, where the bytecode is converted to machine code and run. C# supports important object-oriented concepts like classes, objects, inheritance, polymorphism, abstraction and encapsulation. Classes define the attributes and behaviors of objects, and objects are instantiated from classes. Constructors initialize new objects.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
Object oriented programming involves modeling real-world entities as objects that encapsulate both data and behavior. Programmers define classes that specify the attributes and methods of these objects. This is a different approach than traditional procedural programming, as it focuses on objects rather than functions.
This document provides an introduction to Objective-C, including:
- Objective-C is a programming language used by Apple for iOS and Mac apps that is a superset of C and adds object-oriented capabilities.
- The language consists of objects, classes, methods, and messages that allow objects to communicate with each other.
- Keywords like @interface, @implementation, and @protocol are used to define classes, categories, and protocols.
- The document discusses features like properties, memory management, and differences between instance and class methods.
This document summarizes a presentation on JavaScript essentials for Java developers. It discusses JavaScript object literals, core objects like Array and Date, JSON, and JavaScript classes. Object literals allow creating objects without classes by using this and properties/methods. Core objects like Array, Date, Math and String are explored. JSON is introduced as a lightweight data interchange format. JavaScript classes are explained using the constructor function pattern and prototype properties to add methods to all objects.
This document discusses object-oriented programming concepts in Objective-C such as classes, inheritance, polymorphism, and exceptions. It covers creating interface and implementation files, using properties and methods, inheritance hierarchies with subclasses, overriding methods, abstract classes, polymorphism through dynamic binding, and exceptions. Key topics include creating .h and .m files to define a class, using self to reference the current object, returning objects from methods, and extending classes through inheritance while allowing method overriding.
The document discusses various topics in Objective-C including variables, data types, categories, protocols, and composite objects. It provides code examples to illustrate initializing objects, variable scope, enumerated data types, typedefs, data type conversion, categories, class extensions, protocols, delegates, and composite objects in Objective-C and compares some of these concepts to Java.
This document provides an overview of test automation using Selenium. It discusses reasons to automate testing such as supporting regression testing and finding defects missed by manual testing. It also discusses when not to automate, such as when an application's behavior is unstable. The document then covers the Selenium framework, its components like Selenium IDE and WebDriver, and languages it supports like Java. It also discusses concepts in object-oriented programming relevant to test automation like classes, objects, inheritance and more.
This document discusses classes and objects in Python. It defines what a class and object are, how to create classes and objects in Python, and provides an example Employee class with two employee objects. A class defines the blueprint for an object, containing attributes and methods. An object is an instance of a class. To create a class in Python, the class keyword is used followed by the class name and contents in a suite. Objects are created by calling the class and passing arguments to its __init__ method. Methods can then be accessed using dot notation on the object.
This document provides an overview of object oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism and more. It also outlines the syllabus for a course on OOP with Java, covering topics like arrays, strings, vectors, exception handling, GUI programming and more. Finally, it provides some examples of basic Java code.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
Batteries -Introduction – Types of Batteries – discharging and charging of battery - characteristics of battery –battery rating- various tests on battery- – Primary battery: silver button cell- Secondary battery :Ni-Cd battery-modern battery: lithium ion battery-maintenance of batteries-choices of batteries for electric vehicle applications.
Fuel Cells: Introduction- importance and classification of fuel cells - description, principle, components, applications of fuel cells: H2-O2 fuel cell, alkaline fuel cell, molten carbonate fuel cell and direct methanol fuel cells.
Design and optimization of ion propulsion dronebjmsejournal
Electric propulsion technology is widely used in many kinds of vehicles in recent years, and aircrafts are no exception. Technically, UAVs are electrically propelled but tend to produce a significant amount of noise and vibrations. Ion propulsion technology for drones is a potential solution to this problem. Ion propulsion technology is proven to be feasible in the earth’s atmosphere. The study presented in this article shows the design of EHD thrusters and power supply for ion propulsion drones along with performance optimization of high-voltage power supply for endurance in earth’s atmosphere.
Software Engineering and Project Management - Introduction, Modeling Concepts...Prakhyath Rai
Introduction, Modeling Concepts and Class Modeling: What is Object orientation? What is OO development? OO Themes; Evidence for usefulness of OO development; OO modeling history. Modeling
as Design technique: Modeling, abstraction, The Three models. Class Modeling: Object and Class Concept, Link and associations concepts, Generalization and Inheritance, A sample class model, Navigation of class models, and UML diagrams
Building the Analysis Models: Requirement Analysis, Analysis Model Approaches, Data modeling Concepts, Object Oriented Analysis, Scenario-Based Modeling, Flow-Oriented Modeling, class Based Modeling, Creating a Behavioral Model.
Applications of artificial Intelligence in Mechanical Engineering.pdfAtif Razi
Historically, mechanical engineering has relied heavily on human expertise and empirical methods to solve complex problems. With the introduction of computer-aided design (CAD) and finite element analysis (FEA), the field took its first steps towards digitization. These tools allowed engineers to simulate and analyze mechanical systems with greater accuracy and efficiency. However, the sheer volume of data generated by modern engineering systems and the increasing complexity of these systems have necessitated more advanced analytical tools, paving the way for AI.
AI offers the capability to process vast amounts of data, identify patterns, and make predictions with a level of speed and accuracy unattainable by traditional methods. This has profound implications for mechanical engineering, enabling more efficient design processes, predictive maintenance strategies, and optimized manufacturing operations. AI-driven tools can learn from historical data, adapt to new information, and continuously improve their performance, making them invaluable in tackling the multifaceted challenges of modern mechanical engineering.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
Discover the latest insights on Data Driven Maintenance with our comprehensive webinar presentation. Learn about traditional maintenance challenges, the right approach to utilizing data, and the benefits of adopting a Data Driven Maintenance strategy. Explore real-world examples, industry best practices, and innovative solutions like FMECA and the D3M model. This presentation, led by expert Jules Oudmans, is essential for asset owners looking to optimize their maintenance processes and leverage digital technologies for improved efficiency and performance. Download now to stay ahead in the evolving maintenance landscape.
1. James Tam
Introduction To Object-
Oriented Programming
Basic Object-Oriented principles such
as encapsulation, overloading as well
the object-oriented approach to
design.
2. James Tam
Reminder: What You Know
•There are different approaches to writing computer programs.
•They all involve decomposing your programs into parts.
•What is different between the approaches (how the
decomposition occurs)/(criteria used for breaking things
down”)
•There approach to decomposition you have been introduced
to thus far:
-Procedural
-Object-Oriented (~2 weeks for CPSC 231)
3. James Tam
An Example Of The Procedural Approach
(Presentation Software)
•Break down the program by what it does (described with
actions/verbs)
Filing Editing Helping
…
Creating
new
document
Opening a
document
Saving a
document
… Exiting
program
PowerPoint
4. James Tam
What You Will Learn
• How to break your program down into objects (New term:
“Object-Oriented programming”)
• This and related topics comprise most of the remainder of the
course
5. James Tam
• Break down the program into entities (classes/objects -
described with nouns)
An Example Of The Object-Oriented Approach
(Simulation)
Zoo
Animals Buildings
Visitors
Staff
Admin
Animal
care
Lions
Tigers
Bears (oh
my!)
ETC.
6. James Tam
Classes/Objects
• Each class of object includes descriptive data.
-Example (animals):
•Species
•Color
•Length/height
•Weight
•Etc.
• Also each class of object has an associated set of actions
-Example (animals):
•Sleeping
•Eating
•Excreting
•Etc.
7. James Tam
Example Exercise: Basic Real-World Alarm
Clock
• What descriptive data is needed?
• What are the possible set of actions?
8. James Tam
Additional Resources
•A good description of the terms used in this section (and terms
used in some of the later sections).
http://docs.oracle.com/javase/tutorial/java/concepts/
•A good walk through of the process of designing an object-
oriented program, finding the candidate objects e.g., how to
use the “find a noun’”approach and some of the pitfalls of this
approach.
http://archive.eiffel.com/doc/manuals/technology/oosc/finding/page.ht
ml
9. James Tam
Types In Computer Programs
• Programming languages typically come with a built in set of
types that are known to the translator
int num;
// 32 bit whole number (e.g. operations: +, -, *, /, %)
String s = "Hello";
// Unicode character information (e.g. operation:
concatenation)
• Unknown types of variables cannot be arbitrarily declared!
Person tam;
// What info should be tracked for a Person
// What actions is a Person capable of
// Compiler error!
10. James Tam
A Class Must Be First Defined
• A class is a new type of variable.
• The class definition specifies:
-What descriptive data is needed?
•Programming terminology: attributes = data (New definition)
-What are the possible set of actions?
•Programming terminology: methods = actions (new definition)
•A method is the Object-Oriented equivalent of a function
11. James Tam
Defining A Java Class
Format:
public class <name of class>
{
attributes
methods
}
Example (more explanations coming shortly):
public class Person
{
private int age; // Attribute
public Person() { // Method
age = in.nextInt();
}
public void sayAge() {// Method
System.out.println("My age is " + age);
}
}
12. James Tam
The First Object-Oriented Example
• Program design: each class definition (e.g., public class
<class name>) must occur its own “dot-java” file).
• Example program consists of two files in the same directory:
-(From now on your programs must be laid out in a similar fashion):
-Driver.java
-Person.java
-Full example: located in UNIX under:
/home/219/examples/intro_OO/first_helloOO
13. James Tam
The Driver Class
public class Driver
{
public static void main(String [] args)
{
Person aPerson = new Person();
aPerson.sayHello();
}
}
// Class person
public void sayHello()
{
...
}
14. James Tam
Class Person
public class Person
{
public void sayHello()
{
System.out.println("I don't wanna say hello.");
}
}
15. James Tam
New Concepts: Classes Vs. Objects
• Class:
-Specifies the characteristics of an entity but is not an instance of that
entity
-Much like a blue print that specifies the characteristics of a building
(height, width, length etc.)
www.colorbox.com
16. James Tam
New Concepts: Classes Vs. Objects (2)
• Object:
-A specific example or instance of a class.
-Objects have all the attributes specified in the class definition
Images: James Tam
17. James Tam
main() Method
•Language requirement: There must be a main() method - or
equivalent – to determine the starting execution point.
•Style requirement: the name of the class that contains main()
is often referred to as the “Driver” class.
-Makes it easy to identify the starting execution point in a big program.
•Do not instantiate instances of the Driver1
•For now avoid:
-Defining attributes for the Driver1
-Defining methods for the Driver (other than the main() method)1
1 Details may be provided later in this course
18. James Tam
Compiling Multiple Classes
•One way (safest) is to compile all code (dot-Java) files when
any code changes.
•Example:
-javac Driver.java
-javac Person.java
-(Alternatively use the ‘wildcard’): javac *.java
19. James Tam
Why Must Classes Be Defined
• Some classes are already pre-defined (included) in a
programming language with a list of attributes and methods
e.g., String
• Why don’t more classes come ‘built’ into the language?
• The needs of the program will dictate what attributes and
methods are needed.
20. James Tam
Defining The Attributes Of A Class In Java
• Attributes can be variable or constant (preceded by the
‘final’ keyword), for now stick to the former.
• Format:
<access modifier>1 <type of the attribute> <name of the attribute>;
• Example:
public class Person
{
private int age;
}
1) Although other options may be possible, attributes are almost always set to private (more on this
later).
21. James Tam
New Term: Object State
• Similar to how two variables can contain different data.
• Attributes: Data that describes each instance or example of a
class.
• Different objects have the same attributes but the values of
those attributes can vary
-Reminder: The class definition specifies the attributes and methods for all
objects
• Example: two ‘monster’ objects each have a health attribute
but the current value of their health can differ
• The current value of an object’s attribute’s determines it’s
state.
Age: 35
Weight: 192
Age: 50
Weight: 125
Age: 0.5
Weight: 7
www.colourbox.com
22. James Tam
Defining The Methods Of A Class In Java
Format:
<access modifier>1 <return type2> <method name> (<p1 type> <p1 name>, <p2 type>
<p2 name>…)
{
<Body of the method>
}
Example:
public class Person
{
// Method definition
public void sayAge() {
System.out.println("My age is " + age);
}
}
1) For now set the access modifier on all your methods to ‘public’ (more on this later).
2) Return types: includes all the built-in ‘simple’ types such as char, int, double…arrays
and classes that have already been defined (as part of Java or third party extras)
23. James Tam
Parameter Passing: Different Types
Parameter
type
Format Example
Simple types <method>(<type> <name>) method(int x, char y) { ... }
Objects <method>(<class> <name>) method(Person p) { ... }
Arrays <method>(<type> []… <name>) method(Map [][] m) { ... }
When calling a method, only the names of the parameters must be
passed e.g., System.out.println(num);
24. James Tam
Return Values: Different Types
Return type Format Example
Simple types <type> <method>() int method() { return(0); }
Objects <class> <method>() Person method() {
Person p = new Person();
return(p);
}
Arrays <type>[]... <method>() Person [] method() {
Person [] p = new
Person[3];
return(p);
}
25. James Tam
What Are Methods
• Possible behaviors or actions for each instance (example) of a
class.
Walk()
Talk()
Walk()
Talk()
Fly()
Swim()
26. James Tam
Instantiation
• New definition: Instantiation, creating a new instance or
example of a class.
• Instances of a class are referred to as objects.
• Format:
<class name> <instance name> = new <class name>();
• Examples:
Person jim = new Person();
Scanner in = new Scanner(System.in);
Creates new object
Variable names: ‘jim’,
‘in’
27. James Tam
•New term: A special method to initialize the attributes of an object as the
objects are instantiated (created).
•The constructor is automatically invoked whenever an instance of the class
is created e.g., Person aPerson = new Person();
•Constructors can take parameters but never have a return
type.
Constructor
Constructor
Call to constructor
(creates something
‘new’)
Object
x
y
z
Object
x = 1
y = 2
z = 3
class Person {
// Constructor
public Person() {
…
}
}
28. James Tam
New Term: Default Constructor
• Takes no parameters
• If no constructors are defined for a class then a default
constructor comes ‘built-into’ the Java language.
• e.g.,
class Driver {
main() {
Person aPerson = new Person();
}
}
class Person {
private int age;
}
Do
previous
example
but with
constructo
r setting
arguments
show how
attributes
can be set
at run time
rather than
fixed
29. James Tam
Calling Methods (Outside The Class)
• You’ve already done this before with pre-created classes!
• First create an object (previous slides)
• Then call the method for a particular variable.
• Format:
<instance name>.<method name>(<p1 name>, <p2 name>…);
• Examples:
Person jim = new Person();
jim.sayName();
// Previously covered example, calling Scanner class method
Scanner in = new Scanner(System.in);
System.out.print("Enter your age: ");
age = in.nextInt();
Scanner
variable
Calling
method
30. James Tam
Calling Methods: Outside The Class You’ve
Defined
• Calling a method outside the body of the class (i.e., in another
class definition)
• The method must be prefaced by a variable (actually a
reference to an object – more on this later).
public class Driver {
public static void main(String [] args) {
Person bart = new Person();
Person lisa = new Person();
// Incorrect! Who ages?
becomeOlder();
// Correct. Happy birthday Bart!
bart.becomeOlder();
}
}
31. James Tam
Calling Methods: Inside The Class
• Calling a method inside the body of the class (where the
method has been defined)
-You can just directly refer to the method (or attribute)
public class Person {
private int age;
public void birthday() {
becomeOlder(); // access a method
}
public void becomeOlder() {
age++; // access an attribute
}
32. James Tam
Second Object-Oriented Example
• Learning concepts:
-Attributes
-Constructors
-Accessing class attributes in a class method
• Location of full example:
/home/219/examples/intro_OO/second_attributeConstructor
33. James Tam
Class Driver
public class Driver
{
public static void main(String [] args)
{
Person jim = new Person();
jim.sayAge();
}
}
public Person() {
Scanner in = new
Scanner(System.in);
System.out.print("Enter age: ");
age = in.nextInt();
}
public void sayAge() {
System.out.println
("My age is " + age);
}
34. James Tam
Class Person
public class Person
{
private int age;
public Person()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter age: ");
age = in.nextInt();
}
public void sayAge()
{
System.out.println("My age is " + age);
}
}
35. James Tam
Creating An Object
• Two stages (can be combined but don’t forget a step)
-Create a variable that refers to an object e.g., Person jim;
-Create a *new* object e.g., jim = new Person();
•The keyword ‘new’ calls the constructor to create a new object in memory
-Observe the following
Person jim;
jim = new Person(12);
jim = new Person(22);
jim null
Jim is a reference to a Person
object
age =22
age =12
36. James Tam
Terminology: Methods Vs. Functions
• Both include defining a block of code that be invoked via the
name of the method or function (e.g., print() )
• Methods a block of code that is defined within a class
definition (Java example):
public class Person
{
public Person() { ... }
public void sayAge() { ... }
}
• Every object that is an instance of this class (e.g., jim is an
instance of a Person) will be able to invoke these methods.
Person jim = new Person();
jim.sayAge();
37. James Tam
Terminology: Methods Vs. Functions (2)
• Functions a block of code that is defined outside or independent of a class
(Python example – it’s largely not possible to do this in Java):
# Defining method sayBye()
class Person:
def sayBye(self):
print("Hosta lavista!")
# Method are called via an object
jim = Person()
jim.sayBye()
# Defining function: sayBye()
def sayBye():
print("Hosta lavista!")
# Functions are called without creating an object
sayBye()
38. James Tam
Methods Vs. Functions: Summary & Recap
Methods
•The Object-Oriented
approach to program
decomposition.
•Break the program down into
classes.
•Each class will have a number
of methods.
•Methods are invoked/called
through an instance of a class
(an object).
Functions
•The procedural (procedure =
function) approach to
program decomposition.
•Break the program down into
functions.
•Functions can be invoked or
called without creating any
objects.
39. James Tam
Second Example: Second Look
Calls in Driver.java
Person jim = new Person();
jim.sayAge();
Person.java
public class Person {
private int age;
public Person() {
age = in.nextInt();
}
public void sayAge() {
System.out.println("My age
is " + age);
}
}
More is needed:
•What if the attribute ‘age’ needs to
be modified later?
•How can age be accessed but not
just via a print()?
40. James Tam
Viewing And Modifying Attributes
1) New terms: Accessor methods: ‘get()’ method
-Used to determine the current value of an attribute
-Example:
public int getAge()
{
return(age);
}
2) New terms: Mutator methods: ‘set()’ method
-Used to change an attribute (set it to a new value)
-Example:
public void setAge(int anAge)
{
age = anAge;
}
41. James Tam
Version 2 Of The Second (Real) O-O Example
Location:
/home/219/examples/intro_OO/third_accesorsMutators
42. James Tam
Class Person
• Notable differences: constructor is redesigned, getAge()
replaces sayAge(), setAge() method added
public class Person
{
private int age;
public Person() {
…
age = in.nextInt();
}
public void sayAge() {
System.out.println("My age
is " + age);
}
}
public class Person
{
private int age;
public Person() {
age = 0;
}
public int getAge() {
return(age);
}
public void setAge
(int anAge){
age = anAge;
}
}
43. James Tam
Class Driver
public class Driver
{
public static void main(String [] args)
{
Person jim = new Person();
System.out.println(jim.getAge());
jim.setAge(21);
System.out.println(jim.getAge());
}
}
44. James Tam
Constructors
•Constructors are used to initialize objects (set the attributes) as
they are created.
•Different versions of the constructor can be implemented with
different initializations e.g., one version sets all attributes to
default values while another version sets some attributes to
the value of parameters.
•New term: method overloading, same method name, different
parameter list.
public Person(int anAge) { public Person() {
age = anAge; age = 0;
name = "No-name"; name = "No-name";
}
}
// Calling the versions (distinguished by parameter list)
Person p1 = new Person(100); Person p2 = new Person();
45. James Tam
Example: Multiple Constructors
•Location:
/home/219/examples/intro_OO/fourth_constructorOverloading
46. James Tam
Class Person
public class Person
{
private int age;
private String name;
public Person()
{
System.out.println("Person()");
age = 0;
name = "No-name";
}
47. James Tam
Class Person(2)
public Person(int anAge) {
System.out.println("Person(int)");
age = anAge;
name = "No-name";
}
public Person(String aName) {
System.out.println("Person(String)");
age = 0;
name = aName;
}
public Person(int anAge, String aName) {
System.out.println("Person(int,String)");
age = anAge;
name = aName;
}
48. James Tam
Class Person (3)
public int getAge() {
return(age);
}
public String getName() {
return(name);
}
public void setAge(int anAge) {
age = anAge;
}
public void setName(String aName) {
name = aName;
}
}
49. James Tam
Class Driver
public class Driver {
public static void main(String [] args) {
Person jim1 = new Person(); // age, name default
Person jim2 = new Person(21); // age=21
Person jim3 = new Person("jim3"); // name=“jim3”
Person jim4 = new Person(65,"jim4");
// age=65, name = “jim4”
System.out.println(jim1.getAge() + " " +
jim1.getName());
System.out.println(jim2.getAge() + " " +
jim2.getName());
System.out.println(jim3.getAge() + " " +
jim3.getName());
System.out.println(jim4.getAge() + " " +
jim4.getName());
}
}
50. James Tam
New Terminology: Method Signature
•Method signatures consist of: the type, number and order of
the parameters.
•The signature will determine the overloaded method called:
Person p1 = new Person();
Person p2 = new Person(25);
51. James Tam
Overloading And Good Design
•Overloading: methods that implement similar but not identical
tasks.
•Examples include class constructors but this is not the only
type of overloaded methods:
System.out.println(int)
System.out.println(double)
etc.
For more details on class System see:
- http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html
• Benefit: just call the method with required parameters.
52. James Tam
Method Overloading: Things To Avoid
• Distinguishing methods solely by the order of the
parameters.
m(int,char);
Vs.
m(char,int);
• Overloading methods but having an identical
implementation.
• Why are these things bad?
53. James Tam
Method Signatures And Program Design
•Unless there is a compelling reason do not change the
signature of your methods!
class Foo
{
void fun()
{
}
}
Before:
class Foo
{
void fun(int num)
{
}
}
After:
public static void main ()
{
Foo f = new Foo();
f.fun()
}
This change
has broken
me!
54. James Tam
Graphical Summary Of Classes
• UML (Unified modeling language) class diagram
-Source “Fundamentals of Object-Oriented Design in UML” by Booch,
Jacobson, Rumbaugh (Dorset House Publishing: a division of Pearson)
2000
-UML class diagram provides a quick overview about a class (later you
we’ll talk about relationships between classes)
• There’s many resources on the Safari website:
-http://proquest.safaribooksonline.com.ezproxy.lib.ucalgary.ca/
-Example “Sams Teach Yourself UML in 24 Hours, Third Edition”
(concepts)
-Hour 3: Working with Object-Orientation
-Hour 4: Relationships
- Hour 5: Interfaces (reference for a later section of notes “hierarchies”)
55. James Tam
UML Class Diagram
<Name of class>
-<attribute name>: <attribute type>
+<method name>(p1: p1type; p2 : p2 type..) :
<return type>
Person
-age:int
+getAge():int
+getFriends():Person []
+setAge(anAge:int):void
56. James Tam
Why Bother With UML?
•It combined a number of different approaches and has become
the standard notation.
•It’s the standard way of specifying the major parts of a
software project.
•Graphical summaries can provide a useful overview of a
program (especially if relationships must be modeled)
-Just don’t over specify details
57. James Tam
Back To The ‘Private’ Keyword
• It syntactically means this part of the class cannot be accessed
outside of the class definition.
-You should always do this for variable attributes, very rarely do this for
methods (more later).
• Example
public class Person {
private int age;
public Person() {
age = 12; // OK – access allowed here
}
}
public class Driver {
public static void main(String [] args) {
Person aPerson = new Person();
aPerson.age = 12; // Syntax error: program won’t
// compile!
}
58. James Tam
New Term: Encapsulation/Information Hiding
•Protects the inner-workings (data) of a class.
•Only allow access to the core of an object in a controlled
fashion (use the public parts to access the private sections).
-Typically it means public methods accessing private attributes via
accessor and mutator methods.
-Controlled access to attributes:
•Can prevent invalid states
•Reduce runtime errors
private
data
public
method
public
method
public
method
set data
(mutator
method)
get data
(accessor
method)
59. James Tam
How Does Hiding Information Protect Data?
•Protects the inner-workings (data) of a class
-e.g., range checking for inventory levels (0 – 100)
•Location of the online example:
-/home/219/examples/intro_OO/fifth_noProtection
Driver Inventory
+stockLevel: int
+Inventory()
61. James Tam
Class Driver
public class Driver
{
public static void main(String [] args)
{
Inventory chinook = new Inventory();
chinook.stockLevel = 10;
System.out.println("Stock: " + chinook.stockLevel);
chinook.stockLevel = chinook.stockLevel + 10;
System.out.println("Stock: " + chinook.stockLevel);
chinook.stockLevel = chinook.stockLevel + 100;
System.out.println("Stock: " + chinook.stockLevel);
chinook.stockLevel = chinook.stockLevel - 1000;
System.out.println("Stock: " + chinook.stockLevel);
}
}
62. James Tam
Utilizing Information Hiding: An Example
•Location of the online example:
-/home/219/examples/intro_OO/sixth_encapsulation
+MIN: int
+MAX: int
+CRITICAL: int
-stockLevel: int
+inventoryTooLow():boolean
+add(amount : int)
+remove(amount : int)
+showStockLevel()
Inventory
Driver
63. James Tam
Class Inventory
public class Inventory
{
public final int CRITICAL = 10;
public final int MIN = 0;
public final int MAX = 100;
private int stockLevel = 0;
public boolean inventoryTooLow()
{
if (stockLevel < CRITICAL)
return(true);
else
return(false);
}
64. James Tam
Class Inventory (2)
public void add(int amount)
{
int temp;
temp = stockLevel + amount;
if (temp > MAX)
{
System.out.println();
System.out.print("Adding " + amount +
" item will cause stock ");
System.out.println("to become greater than " + MAX + "
units (overstock)");
}
else
{
stockLevel = temp;
}
}
65. James Tam
Class Inventory (3)
public void remove(int amount)
{
int temp;
temp = stockLevel - amount;
if (temp < MIN)
{
System.out.print("Removing " + amount +
" item will cause stock ");
System.out.println("to become less than " + MIN + " units
(understock)");
}
else
{
stockLevel = temp;
}
}
public String showStockLevel ()
{ return("Inventory: " + stockLevel); }
}
66. James Tam
The Driver Class
public class Driver
{
public static void main (String [] args)
{
Inventory chinook = new Inventory();
chinook.add(10);
System.out.println(chinook.showStockLevel());
chinook.add (10);
System.out.println(chinook.showStockLevel());
chinook.add (100);
System.out.println(chinook.showStockLevel());
chinook.remove (21);
System.out.println(chinook.showStockLevel());
// JT: The statement below won't work and for good reason!
// chinook.stockLevel = -999;
}
}
67. James Tam
Add(): Try Adding 100 items to 20 items
public void add(int amount)
{
int temp;
temp = stockLevel + amount;
if (temp > MAX)
{
System.out.println();
System.out.print("Adding " + amount +
" item will cause stock ");
System.out.println("to become greater than " + MAX +
" units (overstock)");
}
else
{
stockLevel = temp;
}
} // End of method add
68. James Tam
Remove(): Try To Remove 21 Items From 20
Items
public void remove(int amount)
{
int temp;
temp = stockLevel - amount;
if (temp < MIN)
{
System.out.print("Removing " + amount +
" item will cause stock ");
System.out.println("to become less than " + MIN + " units
(understock)");
}
else
{
stockLevel = temp;
}
}
public String showStockLevel ()
{ return("Inventory: " + stockLevel); }
}
69. James Tam
New Terms And Definitions
• Object-Oriented programming
• Class
• Object
• Class attributes
• Class methods
• Object state
• Instantiation
• Constructor (and the Default constructor)
• Method
• Function
70. James Tam
New Terms And Definitions (2)
• Accessor method (“get”)
• Mutator method (“set”)
• Method overloading
• Method signature
• Encapsulation/information hiding
• Multiplicity/cardinality
71. James Tam
After This Section You Should Now Know
•How to define classes, instantiate objects and access different
part of an object
•What is a constructor and how is it defined and used
•What are accessor and mutator methods and how they can be
used in conjunction with encapsulation
•What is method overloading and why is this regarded as good
style
•How to represent a class using class diagrams (attributes,
methods and access permissions) and the relationships
between classes
•What is encapsulation/information-hiding, how is it done and
why is it important to write programs that follow this principle
72. James Tam
Copyright Notification
• “Unless otherwise indicated, all images in this presentation
are used with permission from Microsoft.”
slide 72