Download presentation
Presentation is loading. Please wait.
Published byPhilippa Jacobs Modified over 8 years ago
2
DR. NERMIN HAMZA Java: Lecture 2
3
Java life cycle 2 Java programs normally undergo four phases Edit Programmer writes program (and stores program on disk) Compile Compiler creates bytecodes from program (.class) Load Class loader stores bytecodes in memory Execute Interpreter: translates bytecodes into machine language
4
Java life cycle 3 Source code (.java) Compiled into Byte codes (.class), as (.exe) in c++ – The Java Application Programming Interface (API) a large collection of ready-made software components. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. – Java Virtual Machine (JVM) – Machine code
5
Java life, cont.. 4
6
Compiling and Running Java code javac HelloWorld.java java HelloWorld
7
Why OO Programming? Better concepts and tools to model and represent the real world as closely as possible (including concurrency, e.g., in Windows GUI) => model of reality => behavior modeling
8
Why OO Programming? Better reusability & extensibility (inheritance) => reduce the time/cost of development Enhanced maintainability & improved reliability – “ Encapsulation ” and “ Information Hiding ” Object only accessible through the external interface Internal implementation details are not visible outside Localized changes to implementation of classes Completeness: all required operations are defined Independent testing and maintenance Help writing good program more easily
9
What Is an Object? These real-world objects all have states and behaviors. Definition: An object is a software bundle of variables and related methods (function). A common visual representation of a software object.
10
Objects An object is a thing. Example of Objects Customer John Dog Mary Account 238-49-1357 Object ‘type’ Object name
11
Classes A class (e.g., Dog) is a kind of mold or template to create objects (e.g., Mary and DooDoo) An object is an instance of a class. The object belongs to that class Dog Mary Dog DooDoo Instance-of Dog
12
Objects vs. Classes Objects: E.g., a real car. Classes: or types E.g., BMW-500 A Class is a blueprint or template of some objects Object is an Instance of some class.
13
Object Properities 12 Grouping code into individual software objects provides a number of benefits, including: – Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. – Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. – Code re-use: If an object already exists, you can use that object in your program. – Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its
14
Object-Oriented Programming (OOP) Object-Oriented Programming consists of 3 primary ideas: Encapsulation Inheritance Polymorphism
15
Object-Oriented Programming (OOP) Encapsulation We can understand and use a data type without knowing all of its implementation details Neither how the data is represented nor how the operations are implemented We just need to know the interface (or method headers) how to “communicate” with the object. Information hiding Modularity : The implementation details can change at any time without affecting other parts of the program.
16
Object-Oriented Programming (OOP) Inheritance Properties of a data type can be passed down to a sub-type – we can build new types from old ones We can build class hierarchies with many levels of inheritance
17
What Is Inheritance? (extends) Subclasses inherit variables and methods from super classes. Subclasses can Add variables and methods. Override inherited methods. Provide specialized behaviors Abstract classes -- define "generic" behaviors.
18
Object-Oriented Programming (OOP) Polymorphism Operations used with a variable are based on the class of the object being accessed, not the class of the variable Parent type and sub-type objects can be accessed in a consistent way
19
Classes in Java A class -- is a template that describes the data and behavior associated with instances of that class. An object -- instantiate a class you create an object. An object is an instance of some class.
20
Classes in Java The data associated with a class or object is stored in variables. The behavior associated with a class or object is implemented with methods. Methods are similar to the functions or procedures in C.
21
Classes 20 A class is a collection of variables or fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()
22
Class syntax 21 [ ] class [extends ] [implements,,…]{ // method & instance variable } class MyClass extends MySuperClass implements YourInterface { //field, constructor, and method declarations }
23
Class modifier 22 ModifierDescription public (A)Class may be accessed by anyone, anywhere member is accessible anywhere the class is protected (A)member is accessible within the defining package and within subclasses blank (A) ("friendly") may only be accessed within the package private (A)member is only accessible to the class that defines it staticused to declare a toplevel class as opposed to an inner class abstractcannot be instantiated, must be a superclass, used whenever one or more methods are abstract finalClass cannot be inherited
24
Declaring Class 23 The class name, with the initial letter capitalized by convention. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. The class body, surrounded by braces, {}.
25
Adding Fields 24 [ ] [= ]; Zero or more modifiers, such as public or private. The field's type. The field's name.
26
Adding Fields: Class Circle with fields 25 Add fields The fields (data) are also called the instance variables. The variables may instance from primitive data type or Reference public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }
27
Fields Modifier 26 ModifierDescription public (A)Property may be accessed by anyone, anywhere protected (A)may be accessed by methods within the same class or subclasses blank (A) ("friendly") may be accessed by methods within the same package only private (A)may be accessed by methods within the same class only staticthere is only one per class but still there could be more than one per JVM volatileIndicates that Java will read the variable from memory not from individual caches assuring accuracy using concurrency. (not implemented in all JVM's) transientfield should not be serialized finalmakes the variable a constant
28
Declaring member variables 27 Member variables in a class —> fields. Instance Variables (Non-Static Fields) Class Variables (Static Fields) Variables in a method or block of code —> local variables. Variables in method declarations —> parameters.
29
Naming Rules 28 Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter. Subsequent characters may be letters, digits, dollar signs, or underscore characters. White space is not permitted. The name must not be a keyword or reserved word. If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. Example : gearRatio and currentGear
30
29 If your variable stores a constant value, capitalizing every letter and separating subsequent words with the underscore character. static final int NUM_GEARS = 6 Reserved Word
31
Defining Methods 30 [ ] ([ ]){ //method body } Modifiers The return type —the data type of the value returned by the method, or void if the method does not return a value. The method name 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.
32
Adding Methods 31 A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is: Usually the name of the method start with verb type MethodName (parameter-list) { Method-body; }
33
Method Modifier 32 ModifierDescription public (A)Method may be accessed by anyone, anywhere protected (A)may be accessed by methods within the same class or (subclasses anywhere) blank (A) ("friendly")may be accessed by methods within the same package only private (A)may be accessed by methods within the same class only staticcannot be instantiated, are called by classname.method,can only access static variables abstractMethod is defined but contains no implementation code (implementation code is included in the subclass). If a method is abstract then the entire class must be abstract. synchronizedacquire a lock on the class for static methods acquires a lock on the instance for non-static classes finalMethod cannot be overridden
34
Method Naming 33 Method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns. In multi-word names, the first letter of each of the second and following words should be capitalized. The rules for field names apply to method names
35
Overriding Method 34
36
Example : Public class Car { private or public variable-type variable-name; private int speed; private int currentGear = 5; // a constructor! public void brake() { /*... */ } public void changePedalCadence(int x) { /* */ } public void changeGear(int x) { /*... */ } }
37
Adding Methods to Class Circle 36 public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } Method Body
38
Data Abstraction 37 Declare the Circle class, have created a new data type – Data Abstraction Can define variables (objects) of that type: Circle aCircle; Circle bCircle;
39
Class of Circle cont. 38 aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null
40
Creating objects of a class 39 Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;
41
40 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;
42
41 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment
43
Class HelloWorld (Applet version) import java.applet.Applet; import java.awt.Graphics; public class HelloWorld extends Applet { public void paint(Graphics g) { g.drawString("Hello world!", 50, 25); } } inherit Applet
44
Mankind extends Animal public class Animal { private int height = 0; private int weight = 0; public void talk( ) { System.out.println(“Arhh");} } public class Mankind extends Animal { private int iq = 120; public void talk( ) { System.out.println("Hello");} } Mankind is-a Animal Should be in different files One Java file can only have one public class
45
Mankind inherits Animal (C++) class Animal { int height = 0; int weight = 0; public: void talk( ) { System.out.println("Won");} }; class Mankind :public Animal { private: int iq = 120; public: void talk( ) { System.out.println("Hello");} } ; Classes can be in same file In C++, " ; " is required to terminate a class
46
Rectangle Contains Point public class Point { private int x = 0; private int y = 0; } public class Rectangle { private int width = 0; private int height = 0; private Point origin = new Point(); } Should be in different files Car has-a Wheel
47
Constructors, cont. A constructor with no parameters is referred to as a default constructor. Constructors must have the same name as the class itself. Constructors do not have a return type— not even void. Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
48
Constructors Circle(double r) { radius = r; } Circle() { radius = 1.0; } myCircle = new Circle(5.0); Constructors are a special kind of methods that are invoked to construct objects.
49
Class may have many Constructors public class Rectangle { int width = 0; int height = 0; Point origin; // four constructors public Rectangle() { origin = new Point(0, 0); } public Rectangle(Point p) { origin = p; } public Rectangle(int w, int h) { this(new Point(0, 0), w, h); } public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; } // a method for moving the rectangle public void move(int x, int y) { origin.x = x; origin.y = y; } // a method for computing the area of the rectangle public int area() { return width * height; } }
50
Point and it's constructor public class Point { private int x = 0; private int y = 0; // a constructor! public Point(int xxx, int y) { x = xxx; this.y = y; }... Point p = new Point(44,78); this.y this.x
51
Accessing Object/Circle Data 50 Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.