DR. NERMIN HAMZA Java: Lecture 2 Java life cycle 2 Java programs normally undergo four phases  Edit  Programmer writes program (and stores program.

Slides:



Advertisements
Similar presentations
1 Classes and Objects in Java Basics of Classes in Java.
Advertisements

1 Object-Oriented Programming Concepts. 2 Recap from last lecture Variables and types –int count Assignments –count = 55 Arithmetic expressions –result.
Classes and Objects in Java. What Is an Object?. An object is a software bundle of related state and behavior. Software objects are often used to model.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object-oriented Programming Concepts
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Lecture 3. 2 Introduction Java is a true OO language -the underlying structure of all Java programs is classes. Everything must be encapsulated in a class.
Object-Oriented Programming Concepts
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
The Java Programming Language
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
1 Classes and Objects in C++ 2 Introduction Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything.
1 Classes and Objects in Java Basics of Classes in Java.
1 Software Construction Lab 3 Classes and Objects in Java Basics of Classes in Java.
JAVA BASICS Prepared by The Smartpath Information Systems
Inheritance in the Java programming language J. W. Rider.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
11/28/2015B.Ramamurthy1 Object-Oriented Design and Java B.Ramamurthy.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming Paradigms Lecturer Hamza Azeem. What is PP ? Revision of Programming concepts learned in CPLB Learning how to perform “Object-Oriented Programming”
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
CS 139 Objects Based on a lecture by Dr. Farzana Rahman Assistant Professor Department of Computer Science.
Classes, Interfaces and Packages
What Is a Package? A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar.
Lesson 1 1 LESSON 1 l Background information l Introduction to Java Introduction and a Taste of Java.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
By : Robert Apeldorn. What is OOP?  Object-oriented programming is a programming paradigm that uses “objects” to design applications and computer programs.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Topic: Classes and Objects
Working with Java.
University of Central Florida COP 3330 Object Oriented Programming
Inheritance and Polymorphism
Classes and Objects in Java
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Classes and Objects in Java
Classes and Objects in Java
University of Central Florida COP 3330 Object Oriented Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Object Oriented Programming in java
Introducing Java.
Presentation transcript:

DR. NERMIN HAMZA Java: Lecture 2

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

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

Java life, cont.. 4

Compiling and Running Java code javac HelloWorld.java java HelloWorld

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

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

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.

Objects An object is a thing. Example of Objects Customer John Dog Mary Account Object ‘type’ Object name

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

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.

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

Object-Oriented Programming (OOP) Object-Oriented Programming consists of 3 primary ideas:  Encapsulation  Inheritance  Polymorphism

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.

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

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.

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

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.

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.

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()

Class syntax 21 [ ] class [extends ] [implements,,…]{ // method & instance variable } class MyClass extends MySuperClass implements YourInterface { //field, constructor, and method declarations }

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

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, {}.

Adding Fields 24 [ ] [= ]; Zero or more modifiers, such as public or private. The field's type. The field's name.

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 }

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

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.

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

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

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.

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; }

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

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

Overriding Method 34

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) { /*... */ } }

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

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;

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

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() ;

40 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;

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

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

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

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

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

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.

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.

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; } }

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

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)