Topic: Classes and Objects

Slides:



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

Final and Abstract Classes
Classes and Objects in Java
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Tutorial 6 February 4th/5th, 2015
Road Map Introduction to object oriented programming. Classes
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
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.
1 Software Construction Lab 4 Classes and Objects in Java Basics of Classes in Java.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
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.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Objects and Classes Mostafa Abdallah
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
CS 139 Objects Based on a lecture by Dr. Farzana Rahman Assistant Professor Department of Computer Science.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
OOP Basics Classes & Methods (c) IDMS/SQL News
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
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.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Chapter 11 Inheritance and Polymorphism
Final and Abstract Classes
Classes and Objects in Java
Chapter 3: Using Methods, Classes, and Objects
Classes and Objects in Java
Classes and Objects in Java
HIGHLEVEL REVIEW Chapter 9 Objects and Classes
Chapter 9 Inheritance and Polymorphism
Corresponds with Chapter 7
Chapter 6 Methods: A Deeper Look
Chapter 9 Objects and Classes
Java Programming Language
Chapter 11 Inheritance and Polymorphism Part 1
OO Programming Concepts
Final and Abstract Classes
Chapter 6 Objects and Classes
Chapter 7 Objects and Classes
Presentation transcript:

Topic: Classes and Objects Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Reader, Dept. of IT prabhjot.kaur@msit.in 1

Classes and Objects A class consists of variables called fields together with functions called methods or member functions that act on those fields.

General Structure of a Class Members of a class are: fields or variables a class or object's state or attributes methods a class or object's behaviour constructors to make objects each has access control

General Structure of a Class Types of Members fields or variables instance unique values for each object class uses the static modifier same value for all objects methods instance work with both instance and static variables class uses static modifier works with static variables

General Structure of a Class Fields or Variables field or variable holds a single value is strongly typed: must be declared type specifies the kind of value and the variable's behaviour int i = 123; // integer primitive Point pt = null; // object reference pt = new Point (x, y); // coordinates pt has the value of the Point object's address, not the x, y coordinates

Classes and Objects A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area()

Classes and Objects A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition: Bare bone class – no fields, no methods class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] } public class Circle { // my circle class }

Adding Fields: Class Circle with fields Classes and Objects Adding Fields: Class Circle with fields Add fields The fields (data) are also called the instance variables. public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle }

Classes and Objects Adding Methods 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: type MethodName (parameter-list) { Method-body; }

Adding Methods to Class Circle Classes and Objects Adding Methods to Class Circle 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

Classes and Objects Data Abstraction Declare the Circle class, have created a new data type – Data Abstraction Can define variables (objects) of that type: Circle aCircle; Circle bCircle;

Classes and Objects Class of Circle cont. aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle bCircle null null Points to nothing (Null Reference) Points to nothing (Null Reference)

Creating objects of a class Classes and Objects Creating objects of a class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects aCircle = new Circle() ; bCircle = new Circle() ;

Creating objects of a class Classes and Objects Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle;

Creating objects of a class Classes and Objects Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; Before Assignment Before Assignment P aCircle bCircle P aCircle bCircle Q Q

Automatic garbage collection Classes and Objects Automatic garbage collection Q The object does not have a reference and cannot be used in future. The object becomes a candidate for automatic garbage collection. Java automatically collects garbage periodically and releases the memory used to be used in the future.

Accessing Object/Circle Data Classes and Objects Accessing Object/Circle Data Similar to C syntax for accessing data defined in a structure. ObjectName.VariableName ObjectName.MethodName(parameter-list) Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0

Executing Methods in Object/Circle Classes and Objects Executing Methods in Object/Circle Using Object Methods: sent ‘message’ to aCircle Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();

Classes and Objects Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } [raj@mundroo]%: java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =31.400000000000002

Constructors a special kind of method to construct an instance of an object from a class template default constructor is ClassName() created if the class has no constructors instance fields are initialized to default values automatically (see next slide) overloaded constructors: same name with different parameter lists use of “this” to call another constructor

Constructors Java automatically initializes class (static) and object (instance) fields Primitive Data Type Default Value boolean false int, etc. 0 Object Reference Type null - not yet referring to an object

Constructors Constructors this keyword Referencing the current object To call another constructor

Constructor initializes an object's instance fields Constructors Constructor initializes an object's instance fields class MyClass { int maximum; int counter; boolean isBelowMax = true; // override default MyClass(int maximum) { this.maximum = maximum; } MyClass() { this(100); } // calls this class's constructor MyClass(int maximum, int counter) { this.maximum = maximum; // assign local field value this.counter = counter; // to this object's instance isBelowMax = counter < maximum; }

Method Overloading overloading is supported: same method name, different parameter lists parameters passed by value, i.e. by copy primitive data types and object reference types copy of object reference is not a copy of the object type of primitive/object returned or void

Four Levels of Access to a Class or object's members Classes and Objects Four Levels of Access to a Class or object's members private: accessible from within this class only should be standard practice on instance fields to support OO encapsulation default (if you don't specify): accessible from any class in the package protected: accessible from any subclass or any class in the package public: accessible from any class anywhere

Classes and Objects Access Control Levels Access Location Public Protected Default Private protected private Same class Yes Subclass in same pkg. No Other classes in same pkg. Subclass in other Pkg. Non-subclasses in other Pkg.

Static keyword When objects of its class are declared, no copy of a static variable is made Instead, all instances of the class share the same static variable When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object The most common example of a static member is main(). Outside of the class in which static methods are defined, static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the .(dot) operator ClassName.methodName() 27

Static keyword Restrictions: Static methods can only call other static methods. They can only access static data. They can not refer to ‘this’ or ‘super’ in any way. 28

Static Blocks Static block is a block of code prefixed by ‘static’ keyword Gets executed only once Used to initialize static variables class A { static int x; static { x = 10; } public static void main (String args[]) { System.out.println (“ x value is : ”+ x); static block initializes x to 10 Output : x value is : 10 29

Example Program : Static Block class A { static int x = 10; static int y; static void call( int p) { System .out. println(“ x value is :”+x); System .out .println(“ y value is :”+y); System .out .println(“ p value is :”+p); } static { System.out.println(“ static block initialized”); y=x*2; public static void main (String args[]) { call(30); Output x value is : 10 y value is : 20 p value is : 30

Final keyword A variable can be declared as final Doing so prevents its contents from being modified This means that you must initialize a final variable when it is declared Permits us to create typed constants In usage, final is similar to const in C / C++ 31

Example final variables Syntax final type constName = value; Example final int FILE_NEW = 1; final float PI = 3.141519;

Final Variables Subsequent parts of the program may use the above final variables FILE_NEW and PI It is common coding convention to choose all uppercase identifiers for final variables Variables declared as final do not occupy memory on a per-instance basis Thus, a final variable is essentially a constant

Example program : final variables Correct program Wrong program class A { final int X = 10; public static void main (String args[]) { System.out.println(“ X is “+X); } class B { final int X = 10; public static void main(String args[]) { X = 20; System .out. println(“ X is “+X); } final variable should not change

Other Uses Of final The keyword final can also be applied to methods, Its meaning is substantially different than when it is applied to variables

Varargs Newly implemented feature in Java 5.0 Basic syntax type … variableName Argument passed to a method is converted into an array of the same-typed values sum (10,20) sum(new int[] {10,20})

Varargs Example public static void main(String[] args) { System.out.println(“The sum is ” + sum(10,20,30)); } public int sum (double … numbers) int total = 0; for (int i = 0; i < numbers.length; i++) total += numbers[i]; return total; OUTPUT: The sum is 60

Varargs Varargs is done with the … operator. Example. The following constructor public Person (String name, String details… ) Can be called with many different invocations: new Person (“Alexander ”); new Person (“Alexander ”, “Bell ”); new Person (“Alexander ”,”Graham”, “Bell ”);

Exercise: Do one program to demonstrate Varargs concept.

Thank You