1 Classes and Objects in Java Parameter Passing, Delegation, Visibility Control, and Object Cleanup.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

1 Classes and Objects in Java Basics of Classes in Java.
Basic Java Constructs and Data Types – Nuts and Bolts
Classes and Objects in Java
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
Lecture 10 Methods COMP1681 / SE15 Introduction to Programming.
Operator overloading redefine the operations of operators
Color Templates Software Engineering Module: Core of Java Topic: Constructors TALENTSPRINT | © Copyright 2012.
1 public class Newton { public static double sqrt(double c) { double epsilon = 1E-15; if (c < 0) return Double.NaN; double t = c; while (Math.abs(t - c/t)
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Copyright © Recursive GCD Demo public class.
Introduction to Computer Science Robert Sedgewick and Kevin Wayne Recursive Factorial Demo pubic class Factorial {
Chapter 6 Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and.
This is Java Jeopardy.
Programming Methodology (1). Implementing Methods main.
The Point Class public class Point { public double x; public double y; public Point(double x0, double y0) { x = x0; y = y0; } public double distance(Point.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
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.
1 Calling within Static method /* We can call a non static method from a static method but by only through an object of that class. */ class Test1{ public.
Objects contains data and methods Class – type of object Create class first Then object or instance String – defined class String s; // creates instance.
CS18000: Problem Solving and Object-Oriented Programming.
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
METHOD OVERRIDING Sub class can override the methods defined by the super class. Overridden Methods in the sub classes should have same name, same signature.
Övning 4. Repetition göra egna klasser class Rektangel { private double längd; private double bredd; public Rektangel(double l, double b) { this.längd.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Overloading methods review When is the return statement required? What do the following method headers tell us? public static int max (int a, int b)
Writing methods. Calling Methods nameOfMethod(parameters) if method returns something, use that value Math.pow(2, 3) returns 8 System.out.println(Math.pow(2,
1 Software Construction Lab 4 Classes and Objects in Java Basics of Classes in Java.
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Methods F Hello World! F Java program compilation F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters by value F Overloading.
Objects and Classes Mostafa Abdallah
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
The Math class Java provides certain math functions for us. The Math class contains methods and constants that can be very useful. The Math class is like.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
TOPIC 6 Methods F Introducing Methods F Declaring Methods F Calling Methods F Passing Parameters F Pass by Value F Overloading Methods F Method Abstraction.
1 st Semester Module 6 C# Methods – Part II อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer Engineering.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
CLASSES IN JAVA Primitive Types Example of a Class Allocating Objects of a Class Protecting Class data Constructors Static data and Static Methods.
Staples are our staple Building upon our solution.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Introduction to Programming using Java Day 3 and 4 Java Language Basics Review The “For” loop Subroutines The “String” class.
CPSC 233 Tutorial 12 March 4/5 th, TopHat Quiz int[] a = {0}; int[] b = {1}; a = b; What is the value of a[0] i) 0 ii) 1.
Java Memory Management
Java Memory Management
Examples of Classes & Objects
AKA the birth, life, and death of variables.
Interface.
Introduction to Java Programming
Classes & Objects: Examples
Group Status Project Status.
Java Lesson 36 Mr. Kalmes.
Recursive GCD Demo public class Euclid {
CS2011 Introduction to Programming I Methods (II)
AKA the birth, life, and death of variables.
class PrintOnetoTen { public static void main(String args[]) {
METHODS, CLASSES, AND OBJECTS A FIRST LOOK
A Java Application public class Hello { public static void main(String [] args) { System.out.println("Hello, World!"); } } public class.
A Java Application public class Hello { public static void main(String [] args) { System.out.println("Hello, World!"); } } public class.
Chapter 9 Objects and Classes
Unit-1 Introduction to Java
Corresponds with Chapter 5
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

1 Classes and Objects in Java Parameter Passing, Delegation, Visibility Control, and Object Cleanup

2 Contents Review of Static Methods Apply to Circle class Review main method Final data members Parameter Passing Object Delegation Visibility Control Object Cleanup Summary

3 Static Method in Circle class Like class variables, can have class methods too: Accessed with class name Circle c1= new Circle(); Circle c2 = new Cricle(); Cricle c3 = Cricle.bigger(c1,c2); public class Circle { //A class method for the same public static Circle bigger(Circle a, Circle b) { if (a.r > b.r) return a; else return b; }

4 Static Methods in Circle Class Class methods can only access static variables and methods. public class Circle { // class variable, one for the Circle class, how many circles private static int numCircles = 0; public double x,y,r; public static void printNumCircles(){ System.out.println(Number of Circles = + numCircles); } // This is not VALID public static void printRadius(){ { System.out.println(Radius = + r); }

5 Back to HelloWorld [System invokes static main method] // HelloWorld.java: Hello World program class HelloWorld { public static void main(String args[]) { System.out.println(Hello World); }

6 Back to Constants [final can also be made as static] class SquaredNumbers{ static final int MAX_NUMBER = 25; public static void main(String args[]){ final int MAX_NUMBER = 25; int lo = 1; int squared = 0; while (squared <= MAX_NUMBER){ squared = lo * lo; // Calculate square System.out.println(squared); lo = lo + 1; /* Compute the new lo value */ }

7 Parameter passing Method parameters which are objects are passed by reference. Copy of the reference to the object is passed into method, original value unchanged.

8 Parameter passing - Example public class ReferenceTest { public static void main (String[] args) { Circle c1 = new Circle(5, 5, 20); Circle c2 = new Circle(1, 1, 10); System.out.println ( c1 Radius = + c1.getRadius()); System.out.println ( c2 Radius = + c2.getRadius()); parameterTester(c1, c2); System.out.println ( c1 Radius = + c1.getRadius()); System.out.println ( c2 Radius = + c2.getRadius()); } …….. cont

9 Parameter passing - Example public static void parameterTester(Circle circleA, Circle circleB) { circleA.setRadius(15); circleB = new Circle(0, 0, 100); System.out.println ( circleA Radius = + circleA.getRadius()); System.out.println ( circleB Radius = + circleB.getRadius()); }

10 Parameter passing - Example Output – c1 Radius = 20.0 c2 Radius = 10.0 circleA Radius = 15.0 circleB Radius = c1 Radius = 15.0 c2 Radius = 10.0

11 Parameter passing - Example STEP1 – Before calling parameterTester() c1 (5,5,20) c2 (1.1,10) X circleA X circleB X circleA STEP2 – parameterTester(c1, c2) c1 (5,5,20) c2 (1.1,10) circleA circleB circleA STEP3 – circlA.setRadius(15) c1 (5,5,15) c2 (1.1,10) circleA circleB circleA STEP4 – circlB = new Cirlce(0,0,100) c1 (5,5,15) c2 (1.1,10) circleA circleB circleA (0.0,100)

12 Parameter passing - Example STEP5 – After Returning from parameterTester c1 (5,5,15) c2 (1.1,10) X circleA X circleB X circleA

13 Delegation Ability for a class to delegate its responsibilities to another class. A way of making an object invoking services of other objects through containership.

14 Delegation - Example Point xCoord yCoord getXCoord() getYCoord() public class Point { private double xCoord; private double yCoord; // Constructor …………. public double getXCoord(){ return xCoord; } public double getYCoord(){ return yCoord; }

15 Delegation - Example Point xCoord yCoord getXCoord() getYCoord() public class Circle { private Point centre; public double getCentreX(){ return centre.getXCoord(); } public double getCentreY(){ return centre.getYCoord(); } Circle centre getCentreX() getCentreY()

16 Visibility Control: Data Hiding and Encapsulation Java provides control over the visibility of variables and methods, encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on details of class implementation, so you can update without worry Helps in protecting against accidental or wrong usage. Keeps code elegant and clean (easier to maintain)

17 Visibility Modifiers: Public, Private, Protected Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Default (No visibility modifier is specified): it behaves like public in its package and private in other packages. Default Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.

18 Visibility public class Circle { private double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; } }

19 Visibility area Circle circumference Center (x,y) Radius r message Construction time message message Circle

20 Accessors – Getters/Setters public class Circle { private double x,y,r; //Methods to return circumference and area public double getX() { return x;} public double getY() { return y;} public double getR() { return r;} public double setX(double x) { this.x = x;} public double serY(double y) { this.y = y;} public double setR(double r) { this.r = r;} } More on Visibility during Inheritance and Package Discussion

21 Objects Cleanup/Destructor Unlike c and c++, memory deallocation is automatic in java, dont worry about it no dangling pointers and no memory leak problem. Java allows you to define finalizer method, which is invoked (if defined) just before the object destruction. In way, this presents an opportunity to perform record- maintenance operation or cleanup any special allocations made by the user. //done with this circle protected void finalize() throws IOException { Circle.numCircles = Circle.numCircles--; System.out.println(number of circles:+ Circle.num_circles); }

22 Summary Static members play a role similar to the global members of classes. They can only access other static members in the class. Objects can be passed as parameters and they can be used for exchanging messages (data). Delegation enables an object to pass responsibilities to other objects. Encapsulation/Data hiding helps in protecting data from accidental or wrong usage and also offers better security for data. Java clean-ups object resources automatically, however, users can provide finalize() method to do any user-level related clean-up activities.