Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic: Classes and Objects

Similar presentations


Presentation on theme: "Topic: Classes and Objects"— Presentation transcript:

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

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

3 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

4 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

5 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

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

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

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

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

10 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

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

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

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

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

15 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

16 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.

17 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

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

19 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); } java MyMain Radius=5.0 Area=78.5 Radius=5.0 Circumference =

20 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

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

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

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

24 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

25 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

26 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.

27 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

28 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

29 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

30 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

31 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

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

33 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

34 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

35 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

36 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})

37 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

38 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 ”);

39 Exercise: Do one program to demonstrate Varargs concept.

40 Thank You


Download ppt "Topic: Classes and Objects"

Similar presentations


Ads by Google