1 / 23

Encapsulation More on Methods and Classes

Encapsulation More on Methods and Classes. Class Methods There are three types of class members: public, private and protected members: Public : A public member of a class can be accessed by any code in your program. This includes the methods defined inside other classes Private :

meli
Download Presentation

Encapsulation More on Methods 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. Encapsulation More on Methods and Classes

  2. Class Methods • There are three types of class members: public, private and protected members: • Public: • A public member of a class can be accessed by any code in your program. This includes the methods defined inside other classes • Private: • A private member of a class can only be accessed by other members of its class • Protected: • We will learn about them when we get into the concept of inheritance

  3. The default access setting (when no access is specified), is public unless your program is broken into packages. • A package is essentially a grouping of classes. • class MyClass • { • private int alpha; • public int beta; • int gamma; • void setAlpha(int a) • { • alpha = a; • } • int getAlpha() • { • return alpha; • } • } class AccessDemo {public static void main (String args[]) { MyClass ob = new MyClass(); ob.setAlpha(-99); System.out.println("ob.alpha is " + ob.getAlpha()); ob.alpha = 10; // THIS IS WRONG // alpha IS PRIVATE //THE FOLLOWING ARE OK ob.beta = 88; ob.gamma = 99; } }

  4. Inside the class MyClass, “alpha” is specified as private, “beta” is specified as public and “gamma” uses the default access which is public . • Since alpha is private, the statement • Ob.alpha = 10; • produces error because alpha cannot be accessed directly by the methods outside of the class MyClass. • However, other statements such as • Ob.beta = 88 and • Ob.gamma = 99 • are correct because beta and gamma are both public members and can be accessed directly by the methods (such as main) outside the MyClass. • Although access to alpha by code outside of MyClass is not allowed, methods defined directly within MyClass can freely access it. • Hiding the data member to prevent the outside code to access them directly is called encapsulation of data

  5. Passing More Complex Arguments • So far, we have been dealing with simple methods where the arguments passed to the methods had simple data types • It is also possible to pass objects of one class to a method of another class. • class Block • { int a, b, c; • int volume; • Block(int i, int j, int k) • { a = i; b = j; c = k; volume = a*b*c; } • //------------------------------------------- • boolean sameBlock(Block ob) • { • if ((ob.a == a) && (ob.b ==b) &&(ob.c == c) ) return true; • else return false; • } • //------------------------------------------- • boolean sameVolume(Block ob) • { • if (ob.volume == volume) return true; • else return false; • } • }

  6. class PassOb { public static void main (String args[]) { Block ob1 = new Block(10, 2, 5); Block ob2 = new Block(10, 2, 5); Block ob3 = new Block(4,5,4); System.out.println("ob1 same dimensions as ob2: "+ ob1.sameBlock(ob2)); System.out.println("ob1 same dimensions as ob3: "+ ob1.sameBlock(ob3)); System.out.println("ob1 same volume as ob3: "+ ob1.sameVolume(ob3)); } }

  7. How Arguments are Passed • There are two ways that an argument can be passed to a function: call-by-value and call-by-reference • Call-by-value: • This method copies the value of an argument into the formal parameter of the subroutine • Changes made to the parameter of the subroutine have no effect on the argument used to call it. • Call-by-reference: • In this case, a reference to an argument (not the value of the argument) is passed to the parameter • Inside the subroutine, this reference is used to access the actual argument specified in the call. • In Java, when you pass a simple type (short, byte, float, …) to a method, it is passed by value • However, when you pass an object to a method, it is passed by reference

  8. Example of call by value class Test { void noChange(int i, int j) { i = i+j; j = -j; } } //----------------------------------------------------------------- class CallByValue { public static void main (String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.noChange(a, b); System.out.println("a and b after call: "+ a + " " + b); } }

  9. Example of call by Reference class Test { int a, b; Test(int i, int j) { a = i; b = j; } void change(Test ob) { ob.a = ob.a+ ob.b; ob.b = -ob.b; } } //------------------------------------------------------------------------------------------ class CallByReference { public static void main (String args[ ]) { Test ob1 = new Test(15, 20); Test ob2 = new Test (1, 2); System.out.println("ob2.a and ob2.b before call: "+ ob2.a + " " + ob2.b); ob1.change(ob2); System.out.println("ob2.a and ob2.b after call: "+ ob2.a + " " + ob2.b); } }

  10. One interesting point about objects and their behavior as being called by reference is: • When an object reference is passed to a method, the reference itself is passed by use of call-by-value • However, since the value being passed refers to an object, the copy of that value will still refer to the same object.

  11. Returning Objects • A method can return any data type, including class type. • For example, the next example returns a String object that contains a description of an error based on the error code that is passed to it.

  12. class Err • { • String msg; • int severity; • Err(String m, int s) • { • msg = m; • severity = s; • } • } • class ErrInfo • { public static void main (String args[ ]) • { • ErrorInfo err = new ErrorInfo(); • Err e = err.getErrorInfo(2); • System.out.println(e.msg + " severity: " + e.severity); • e = err.getErrorInfo(19); • System.out.println(e.msg + " severity: " + e.severity); • } • } class ErrorInfo { String msg[ ] = {”output Error", "Input Error", "Disk Full", "Index Out-Of-Bounds"}; int howbad[ ] = { 3,3,2,4}; Err getErrorInfo(int i) { if (i>=0 && i<msg.length) return new Err(msg[i], howbad[i]); else return new Err("Invalid Error Code", 0); } }

  13. Method Overloading • In Java, two or more methods with the same class can share the same name, as long as their parameter declarations are different • In this case, we say methods are overloaded • To overload a method, you just need to make different versions of it as long as you make the type and/or the number of parameters of such overloaded methods different

  14. class Overload { void ovlDemo() { System.out.println("No parameters"); } //-------------------------------------------- void ovlDemo(int a) { System.out.println("One int parameter: " + a); } //-------------------------------------------- int ovlDemo(int a, int b) { System.out.println("two int parameter: " + a + " " + b); return a+b; } //-------------------------------------------- double ovlDemo(double a, double b) { System.out.println("two double parameter: " + a + " " + b); return a+b; } }

  15. class OverloadDemo { public static void main (String args[]) { Overload ob = new Overload(); int resI; double resD; ob.ovlDemo(); System.out.println(); ob.ovlDemo(2); System.out.println(); resI = ob.ovlDemo(4,6); System.out.println("Result of ob.ovlDemo(4,6): " + resI); System.out.println(); resD = ob.ovlDemo(1.1, 2.32); System.out.println("result of ob.ovlDemo(1.1, 2.2): " + resD); } }

  16. The overloaded methods may have different return types; however, the different return types is not sufficient for the purpose of overloading. • void ovlDemo(int a) • { • System.out.println("One int parameter: " + a); • } • //-------------------------------------------- • int ovlDemo(int a) • { • System.out.println("One int parameter: " + a); • return a; • } • //--------------------------------------------

  17. Overloading Constructors • Like other methods constructors can also be overloaded • This way you can construct objects in different ways • class MyClass • { int x; • MyClass() • { System.out.println("Inside MyClass()."); • x = 0; • } //-------------------------------------------- • MyClass(int i) • { System.out.println("Inside MyClass(i)."); • x = i; • } //-------------------------------------------- • MyClass(double d) • { System.out.println("Inside MyClass(double)."); • x = (int) d; • } //-------------------------------------------- • MyClass(int i, int j) • { System.out.println("Inside MyClass(int, int)."); • x = i*j; • } • } //------------------------------------------------

  18. class OverloadConsDemo { public static void main (String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(88); MyClass t3 = new MyClass(17.23); MyClass t4 = new MyClass(2,4); System.out.println("t1.x: " + t1.x); System.out.println("t2.x: " + t2.x); System.out.println("t3.x: " + t3.x); System.out.println("t4.x: " + t4.x); } }

  19. Understanding Static • There are occasions when you may want to define a class member that will be used independently of any object of that class • To create such a member, precede its declaration with the keyword static. • When a member is declared static, it can be accessed before any objects of its class are created and without references to any object • It is possible to have both data and methods to be static • The most well-known example of a static member is main() routine

  20. To call a static member M( ) from the class MyClass you can call it as • MyClass.M( ); • This means, a static member of a class can be invoked before any object of that class is instantiated • Further, you may use the name of any objects of the class MyClass to call the static method M( ) • MyClass obj1 = new MyClass(); • Ob1.M( ); • Basically, a static data member is an attribute that is shared between all objects of that class. • Thus, if one object changes the static attribute, other objects notice the changes

  21. class StaticDemo { int x; // a normal variable static int y; // a static variable } //------------------------------------------------ class SDemo { public static void main (String args[]) { StaticDemo ob1 = new StaticDemo(); StaticDemo ob2 = new StaticDemo(); obj1.x = 10; obj2.x = 20; System.out.println("Of course, ob1.x and obj2.x " + "are independent."); System.out.println("ob1.x: " + ob1.x + "\nob2.x: " + ob2.x); System.out.println(); System.out.println("The static variable y is shared."); ob1.y = 19; System.out.println("ob1.y: " + ob1.y + "\nob2.y: " + ob2.y); System.out.println(); System.out.println("The static var y can be accessed thru its class."); StaticDemo.y = 11; System.out.println("StaticDemo.y: " + StaticDemo.y + "\nob1.y: " + ob1.y + "\nob2.y: " + ob2.y); System.out.println(); } } One of the most common reasons that constructors are overloaded is to allow one object to initialize another object

  22. Example of static method • class StaticMeth • { • static int val = 1024; // a static variable • // a static method • static int valDiv2() • { • return val/2; • } • } • //------------------------------------------------ • class SDemo2 • { public static void main (String args[]) • { • System.out.println("val is " + StaticMeth.val); • System.out.println("StaticMeth.valDiv2(): " + • StaticMeth.valDiv2() ); • StaticMeth.val = 4; • System.out.println("val is " + StaticMeth.val); • System.out.println("StaticMeth.valDiv2(): " + • StaticMeth.valDiv2() ); • } • }

  23. Methods declare as static have several restrictions: • 1) They can call only other static methods • 2) They must access only static data • class StaticError • { • int denom = 3; // a normal instance variable • static int val = 1024; // a static variable • // a static method • static in valDivDenom() • { • return val/denom; // This wont compile because • // denom is not static • } • }

More Related