1 / 33

Session 4 - Objects and Classes

Interactive and very important java programming materials

habzel
Download Presentation

Session 4 - Objects and Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter Four Objects & Classes 1

  2. 4.1 Overview of Objects *Object-Oriented programming or OOP revolves around the concept of objects as the basic elements of programs. *These objects are characterized by their properties (or attributes) and behaviors. *The objects in the physical world can easily be modelled as software objects using the properties as data and the behaviors as methods. *Each object is composed of a set of data (properties/attributes) which are variables describing the essential characteristics of the object, and a set of methods (behaviors) that describes how an object behaves-performing some task. *Thus, an object is a software bundle of variables and related methods. The variables and methods in a Java object are formally known as instance variables and instance methods to distinguish them from class variables and class methods. 2

  3. *Objects are instances of a class. *An object is a building block which contains variables and methods. *An object is a software bundle of related state and behavior. Software objects are used to model the real-world objects in everyday life. *Objects interact with each other by passing messages. *Methods and variables that constitute a class are called members of the class. *The data members or variables, defined with in a class are called instance variables. 3

  4. *A Class is a template, a prototype or a blueprint of an object. *A class is a programmer defined type that serves as a blueprint for instances of the class. *It consists of two types of members which are called fields (properties or attributes) and methods. Fields specify the data types defined by the class, while methods specify the operations. *Classes provide the benefit of reusability. Software programmers can use a class over and over again to create many objects. *A class is a template/ blueprint/prototype that defines the form of an object. *A class is a collection of data and methods that operate on that data. *A Class is a blueprint that defines the states and the behaviors common to all objects of a certain kind. 4

  5. 4.2 Defining/Creating/Declaring a Class *A class is created by using the keyword class. General Form: class ClassName { // declare instance variables type var1; type var2; // ... type varN; // declare methods type method1(parameters) { // body of method } type method2(parameters) { // body of method } // ... type methodN(parameters) { // body of method } } Example: // Class declaration with one method. public class Course { // display a welcome message to the Course user public void displayMessage() { System.out.println( “OOP with Java!”); } // end method displayMessage } // end class Course 5

  6. 4.3 Creating/Declaring an Object * Objects are created with new keyword. * The new operator dynamically allocates ( that is, allocates at run time) memory for an object and returns a reference to it. * This reference is, more or less, the address in memory of the object allocated by new. * This reference is then stored in the variable . * Thus , in Java, all class objects must be dynamically allocated. * General Form ClassName obj = new ClassName( ); // Allocate class object 6 obj.MethodName(); //Calling/invoking the Method

  7. 4.3 Creating/Declaring an Object *Alternatively, ClassName obj ; /*declare reference to object contains null value, which indicates that it does not yet point to an actual object*/ obj = new ClassName( ); // Allocate class object Example: Course c = new Course(); //Creating object called c for class Course c.displayMessage(); //Calling the displayMessage() method 7

  8. class Person { String name = “Abebe”; // initializes name int age = 26;// initializes age void setName(String n) { name = n; } //store name String getName() { return name; } // retrieve name void setAge(int a) { age = a; } //store age int getAge() { return age; } // retrieve age } To create an instance (P )of the Person class with a name of “Henok" and an age of 22 Person P= new Person(); P.setName(“Henok"); P.setAge(22); 8

  9. public class Addition { int x,y; public double add() { return x+y; } public class AdditionTest { public static void main(String args[]) { Addition ad = new Addtion(); // Assign values to ad’s instance variables ad.x=5; ad.y=7; sum= ad.add(); System.out.println(“The Sum of ”+ad.x+” and ”+ad.y+” is: ”+sum); } }

  10. *Object reference variables act differently than you expect when an assignment take place. For example: Course c1 = new Course( ); Course c2 = c1; *c1 and c2 will both refer to the same object. The assignment of c1 and c2 did not allocate any memory or copy any part of the original object . It simply makes c2 refer to the same object as does c1. *When an instance is assigned to a variable, that variable is said to hold a reference or point to that object Person g = new Person(“Abebe", 26); Person h = new Person("Abebe", 26); *g and h hold references to two different objects that happen to have identical state *The object creation statement has three parts. Course c = new Course(); 10 Declaration Instantiation Initialization

  11. Declaration * Declare variables of int type as: - int a; //a is a variable which refers to any type of int data. * Declaration: Associates a variable name with an object type. * Classes in java are also types so declare class type variable as: - Course c; //c is a variable which refers to any type of Course.[Used to refer Course object] * Declaring a object variable (Course c; )do not create any object until assigned with a new keyword. 2. Instantiation * The new operator instantiates a class by allocating a memory for a new object. The new operator returns a reference to the object it created and this reference is assigned to the appropriate variable. Course c = new Course(); //Create object called c & reserve/allocate memory to that object * Instantiating a class means creating an object/Instance of a class. 11

  12. Initialization * The object is always initialized by calling a constructor. * A constructor is a special method which has a same name as class and used to initialize the variables of that object. * Course class object is initialized by calling the constructor of Course class: Course( ); // method to retrieve the course name public String getCourseName() { return courseName; } // end method getCourseName // display a welcome message to the Course user public void displayMessage() { // this statement calls getCourseName to get // name of the course this Course represents System.out.println( "Welcome to the”+ getCourseName() ); } // end method displayMessage } // end class Course public class Course { private String courseName; /*Constructor initializes courseName with String supplied as argument*/ public Course(String cname ) { courseName = cname; // initializes courseName } // end constructor } // end class Course // method to set the course name public void setCourseName( String cname ) { courseName = cname;//store the course name } // end method setCourseName 12

  13. // Course constructor used to specify the course name at the time each Course object is created. public class CourseTest { public static void main( String args[] ) { // main method begins program execution // Create Course object Course c1 = new Course(“Comp321 Object Oriented Programming" ); Course c2 = new Course(“Comp222 Fundamentals of Programming II" ); // display initial value of courseName for each Course System.out.println( “Course I Course Name ", c1.getCourseName() ); System.out.println " Course II Course Name ", c2.getCourseName() ); } // end main } // end class CourseTest 13

  14. 4.4 Object Variables * Object variables are instance of a class that are created from the class. public class Student { String studID; char grade; public Student(String id, char g) { //Constructor studID = id; grade = g; } public void displayInfo() { //Method for displaying student info System.out.println(“Student ID=”+studID+” Grade=”+grade); } public class StudentTest { public static void main(String args[]) { String studID = “ETR/400/04”; //Initialize char grade = “B”; //Initialize Student stud = new Student(StudID, grade); //Create object stud.displayInfo(); //Call/Invoke the method } } 14

  15. 4.5 Constructor * A Constructor is a special method in java class that is used to initialize a new object variables. * Constructors have no return type even void. * A constructor has the same name as the class. * For example the constructor of Course class is Course( ); * Constructors cannot return any value not even void. * If we are not providing any constructor for a class than default (no parameter) constructor is automatically provided by the runtime system. * The constructor can be private, public or protected. class Person { String name; int age; Person(String n, int a) { //Constructor to initialize instance variables name & age name = n; age = a; } // . . . } Person p= new Person(“Abebe", 22); //Create instance of a class 15

  16. Default Constructor *When a constructor is not provided in a class, it implicitly has a constructor with no arguments and an empty body. Generally speaking, every class has a constructor. class Student { // Leaving out the constructor is the same as . . . Student() { } } The this Keyword *The this keyword special reference value used inside any instance method to refer to the current object . The value this refers to the object which the current method has been called on . The this keyword can be used where a reference to an object of the current class type is required . class Person { String name; int age; Person(String name, int age) { //Constructor to initialize instance variables name & age this.name = name; this.age = age; } } Now Construct a Person like: Person P = new Person(“Abebe”,22); 16

  17. *The keyword this is used to reference a field/method from inside the same class. *Within an instance method or a constructor, this is a reference to the current object - the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using thethis keywordor without using the this keyword Example, public class Rectangle { int width = 5; int height = 4; public void Display(){ System.out.println("Width and height are: " + this.width + ", " +this.height); } } *To invoke another constructor of current class inside constructor: int x,y; Addition(int x, int y) { this.x=x; this.y=y; } Addition() { this(4, 5); // invoke the current class constructor that takes two int arguments. } 17

  18. public class Point { int x,y; void init (int x , int y) { this.x = x; this.y = y; } void display ( ) { System.out.println (" x = "+ x); System.out.println (" y = "+ y ); } } public class PointTest { public static void main(String[] args) { // TODO code application logic here Point P = new Point() ; P.init(4,3); P.display() ; } public class GradePtAvg { String studID; double gpa; public GradePtAvg(String studID, double gpa) { this.studID = studID; this.gpa = gpa; } String getstudID() { return studID; } double getgpa() { return gpa ; } void setgpa(double g) { gpa = g; } } public class GPATest { public static void main(String[] args) { GradePtAvg gp = new GradePtAvg("123", 3.75); System.out.println(gp.getstudID()); //123 System.out.println(gp.getgpa()); //3.75 gp.setstudID(“124”); //set studID to 124 gp.setgpa(3.5); //set gpa to 3.5 System.out.println(gp. getstudID());//display 124 System.out.println(gp.getgpa()); //display 3.5 } } } Output x = 4 18 y = 3

  19. 4.6 Access Modifiers * Access modifiers define various levels of access between class members and the outside world (other objects). * They allow us to define the encapsulation characteristics of an object. * There are four access modifiers in java: 1. private– Most restrictive, accessible only by its own class 2. protected – Accessible by its own class & derived/sub/child class 3. public - Accessible to anyone, both inside and outside the class(Have global visibility ) 4. default - Accessible to only classes in the same package. No actual keyword for declaring default access modifier, applied by default in the absence of any access modifier. Access Modifier Accessible from own class Accessible from derived class Accessible from objects(Outside class) public Yes Yes Yes protected Yes Yes No private Yes No No 19

  20. 4.7 Methods *Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Just as there are class and instance variables, there are class and instance methods . Instance methods apply and operate on an instance of the class while class methods operate on the class . *A method is a separate piece of code that can be called by a main program or any other method to perform some specific function. *Methods are subroutines that manipulate the data defined by the class and, in many cases, provide access to that data. *A method is the object-oriented term for a procedure or a function that performs some task. *Why do we need to create methods? Why don't we just place all the code inside one big method? The heart of effective problem solving is in problem decomposition. We can do this in Java by creating methods to solve a specific part of the problem. Taking a problem and breaking it into small, manageable pieces is critical to writing large programs. 20

  21. Defining Methods *The type, name and arguments together is referred to as the signature of the method *Method definition has four parts . They are , name of the method, type of object or primitive type the method returns, a list of parameters and body of the method. General form: Return type Arguments Name Returntype methodName(type1 arg1 , type2 arg2 ) { Body // Body of the methods } Example: double computeArea(int base, int height) { double A; return A = (base*height)/2; } 21

  22. *A method has 4 parts: the return type, the name, the arguments, and the body: type name arguments double sqrt(double num) { // a set of operations that compute // the square root of a number } body int isPrime(int num) { //Block of code that checks whether a number is prime or not } int isPerfect(int num) { //Block of code that checks whether a number is perfect or not } 22

  23. Calling/Invoking Methods *The methods are accessed using the dot notation . General form: obj.methodName ( param1, param2 ); Example: public class Area { int len = 10; int wid = 10; public void calculateArea( ) { int area = len * wid ; System .out .println( “ The area of rectangle is “ + area + “ sq. cms “); } } public class AreaTest { public static void main ( String args [ ] ) { Area a= new Area ( ) ; //Creating object a for class Area a.calculateArea ( ) ; //Calling/Invoking the Method } } 23

  24. Method Parameters *Parameters refers to the list of variables in a method declaration. double Area(double height, double width) // 2 parameters height & width double Area(double radius) //1 parameter radius double findSquareRoot(double num ) // 1 parameter num double isPerfect(int num ) //1 parameter num int isEven(int num ) // 1 parameter num Method Arguments[Passing Arguments to Methods] *Arguments are the actual values that are passed in when the method is invoked. Example: int n=6; Perfect P = new Perfect(n) ; // n is actual value called argument passed to method P.isPerfect(); //Invoke/Call the Method isPerfect() int x=3, y=5; Addition A = new Addition(x, y) ; // x & y are actual value called argument passed to method A. Add(); //Invoke/Call the Method Add() int findSquare(int x) { return x*x; } Square s=new Square ( ) ; //Create instance a class called s s.findSquare( 15 ) ; //15 is argument passed to method findSquare() 24

  25. The Method Body *The body of a method is a block specified by curly brackets. The body defines the actions of the method. int isEven(int num ) { if(num%2==0) { System.out.println(“The Number is Even.”); } Method body else { System.out.println(“The Number is Even.”); } } The main Method- A Special Method The main method is where a Java program execution always starts. public static void main(String[] args) { //. . . } 25

  26. The Return Type of a Method *The return type of a method may be any data type. *The type of a method designates the data type of the output it produces. *Methods can also return nothing in which case they are declared void. *Example: double divide(double a, double b) { double answer; answer = a / b; return answer; } void Methods A method of type void has a return statement without any specified value. i.e. return; Any method declared void doesn't return a value. It’s used to branch out of a control flow block and exit the method. return; public void dispalyMsg() { System.out.println(“Hello Computer Science”); } 26

  27. *The return statement is used in a method to output the result of the methods computation. *It has the form: return expression_value; *The type of the expression_value must be the same as the type of the method: double sqrt(double num){ double answer=Math.sqrt(num); //Compute the square root of num and store the value into the variable answer return answer; } *A method exits immediately after it executes the return statement. *Therefore, the return statement is usually the last statement in a method. 27

  28. Recursive Methods * Recursive Method is procedure or a function that calls it self. import java.util.*; public class Factorial { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter a Number: "); int num = s.nextInt(); //Obtain integer input System.out.println(fact(num)); //Calling static method fact() } public static int fact(int n) { if (n <= 1) { return 1; } else { return n*fact(n-1); } } } 28

  29. . Method abs( x ) Description absolute value of x (this method also has float, int and long versions) Example abs( 23.7 ) is 23.7 abs( 0.0 ) is 0.0 abs( -23.7 ) is 23.7 rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( x ) ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0 exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 log( Math.E ) is 1.0 log( Math.E * Math.E ) is 2.0 max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3 min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7 pow( 2.0, 7.0 ) is 128.0 pow( 9.0, 0.5 ) is 3.0 sin( 0.0 ) is 0.0 sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( 0.0 ) is 0.0 trigonometric cosine of x (x is in radians) exponential method ex cos( x ) exp( x ) rounds x to the largest integer not greater than x natural logarithm of x (base e) floor( x ) log( x ) larger value of x and y (this method also has float, int and long versions) smaller value of x and y (this method also has float, int and long versions) x raised to the power y (xy) max( x, y ) min( x, y ) pow( x, y ) trigonometric sine of x (x is in radians) square root of x sin( x ) sqrt( x ) trigonometric tangent of x (x is in radians) tan( x ) 29

  30. Class or Static Variables *Variables are areas allocated by the computer memory to hold data. Class variable Instance variable Class variable is declared by using static keyword. static int a = 4; Instance variable is declared without static keyword. int a = 4; All objects share the single copy of static variable. Belong to the whole class-static member variable. All objects have their own copy of instance variable. Static variable does not depend on the single object because it belongs to a class. Instance variable depends on the object for which it is available. Instance variable cannot be accessed without creating an object. ObjectName.variable Static variable can be accessed without creating an object, by using class name. ClassName.variable 30

  31. Class or Static Methods s Static Method Instance Method Static methods are declared by using static keyword. static type method( ); instance methods are declared without static keyword. type method( ); All objects have their own copy of instance method. All objects share the single copy of static method. Static method does not depend on the single object because it belongs to a class. Instance method depends on the object for which it is available. Static method can be invoked without creating an object, by using class name. ClassName.method( ); Instance method cannot be invoked without creating an object. ObjectName.method( ); Static methods cannot call non-static methods. Non-static methods can call static methods. Static methods cannot access not-static variables. Non-static methods can access static variables. 31 Instance methods can refer to this and super. Static methods cannot refer to this or super.

  32.  When to declare variable as static? When value of the variable remains the same for all class instance created & being used in every instance. They’ll be loaded when a class loads.  Static tells compiler there’s exactly one copy of this variable in existence, no matter how many times class has been instantiated.  Static method or variable is not attached with specific object, but to class as a whole. They are allocated when the class is loaded. Static methods are declared when the behavior of method doesn’t change for each object created [i.e. behaviors of method remain the same for all instances created.] // Demonstrate static variables, methods and blocks. class UseStatic { static int a = 3; static int b; static void meth ( int x ) { System.out.println ( “ x = “ + x ); System.out.println ( “ a = “ + a ); System.out.println ( “ b = “ + b ); System.out.println ( “ Static block initialized . “ ); b = a * 4 ; } public static void main ( String args [ ] ) { meth ( 42 ); } } Output Static block Initialized x = 42 a = 3 b = 12 32

More Related