Sunteți pe pagina 1din 42

CLASSES & METHODS

CLASSES
The general form of a class definition is shown here: class ClassName { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodName1(parameter-list) { // body of method } type methodName2(parameter-list) { // body of method } // ... type methodNameN(parameter-list) { // body of method } }
2

The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. Example:

class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg;//fuel consumption in miles per gallon }
3

Creating Object

Vehicle minivan = new Vehicle(); /* create a Vehicle object called minivan*/ minivan.fuelcap= 16; /* Accessing the member of the Vehicle class */ (or)

Vehicle minivan; /* declare reference to object */ minivan = new Vehicle(); /* allocate a Vehicle object */

Examples
// This program creates two Vehicle objects. class Vehicle { int passengers; int fuelcap; int mpg;} class VehicleDemo { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); int range1, range2; // assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21;
5

// assign values to fields in sportscar sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; // compute the ranges assuming a full tank of gas range1 = minivan.fuelcap * minivan.mpg; range2 = sportscar.fuelcap * sportscar.mpg; System.out.println("Minivan can carry " + minivan.passengers +" with a range of " + range1); System.out.println("Sportscar can carry " + sportscar.passengers + " with a range of " + range2); } } Output: Minivan can carry 7 with a range of 336 Sportscar can carry 2 with a range of 168

Adding a Method
// Add range to Vehicle. class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg; // fuel consumption in miles per gallon // Display the range. void range() { System.out.println("Range is " + fuelcap * mpg); } } class AddMeth { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle();
7

// assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; // assign values to fields in sportscar sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; System.out.print("Minivan can carry " + minivan.passengers +". "); minivan.range(); // display range of minivan System.out.print("Sportscar can carry " + sportscar.passengers +". "); sportscar.range(); // display range of sportscar. } }
8

Constructors
A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Constructors have no return type, not even void. The constructors job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.

Example
// Add a constructor. class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg; // fuel consumption in miles per gallon // This is a constructor for Vehicle. Vehicle(int p, int f, int m) { passengers = p; fuelcap = f; mpg = m; } // Return the range. int range() { return mpg * fuelcap; }
10

// Compute fuel needed for a given distance. double fuelneeded(int miles) { return (double) miles / mpg; } } class VehConsDemo { public static void main(String args[]) { // construct complete vehicles Vehicle minivan = new Vehicle(7, 16, 21); Vehicle sportscar = new Vehicle(2, 14, 12); double gallons; int dist = 252; gallons = minivan.fuelneeded(dist); System.out.println("To go " + dist + " miles minivan needs " +gallons + " gallons of fuel."); gallons = sportscar.fuelneeded(dist); System.out.println("To go " + dist + " miles sportscar needs " +gallons + " gallons of fuel."); } } 11

The this Keyword


this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked.

Vehicle(int p, int f, int m) { this.passengers = p; this.fuelcap = f; this.mpg = m; }


12

Garbage Collection

In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles de-allocation for you automatically. The technique that accomplishes this is called garbage collection.
13

The finalize( ) Method


Sometimes an object will need to perform some action when it is destroyed. To handle such situations, Java provides a mechanism called finalization. To add a finalizer to a class, you simply define the finalize( ) method. The finalize( ) method has this general form:

protected void finalize( ) { // finalization code here


14

Overloading Methods
In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call.

15

Example
class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } //Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: "+a+" " + b); }
16

// overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }

17

Overloading Constructors
class MyClass { int x; MyClass() { System.out.println("Inside x = 0; } MyClass(int i) { System.out.println("Inside x = i; } MyClass(double d) { System.out.println("Inside x = (int) d; } MyClass(int i, int j) { System.out.println("Inside MyClass().");

MyClass(int).");

MyClass(double).");

MyClass(int, int).");

18

x = i * j; } } 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

Passing Objects as Parameters


// Objects may be passed to methods. class Test { int a, b; Test(int i, int j) { a = i; b = j; } /* return true if o is equal to the invoking object */ boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } }
20

class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1==ob2:"+ob1.equals(ob2)); System.out.println("ob1==ob3:"+ob1.equals(ob3)); } }

21

Returning Objects
// Returning an object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } }

22

class RetOb { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase:"+ ob2.a); } }

23

Access Specifiers
/* This program demonstrates the difference between public and private. */ class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) { // set c's value c = i; } int getc() { // get c's value return c; } }
24

class AccessTest { public static void main(String args[]) { Test ob = new Test(); /* These are OK, a and b may be accessed directly */ ob.a = 10; ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
25

static Keyword
class StaticDemo { int x; // a normal instance variable static int y; // a static variable } class SDemo { public static void main(String args[]) { StaticDemo ob1 = new StaticDemo(); StaticDemo ob2 = new StaticDemo(); ob1.x = 10; ob2.x = 20; System.out.println("Of course, ob1.x and ob2.x " + "are independent."); System.out.println("ob1.x: " + ob1.x + "\nob2.x: " + ob2.x);
26

/* Each object shares one copy of a static variable. */ 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("The static variable y can be" + " accessed through its class."); StaticDemo.y = 11; /* Can refer to y through class name */ System.out.println("StaticDemo.y: " + StaticDemo.y + "\nob1.y: " + ob1.y + "\nob2.y: " + ob2.y); } }
27

static Block
// Use a static block class StaticBlock { static double rootOf2; static double rootOf3; static { System.out.println("Inside static block."); rootOf2 = Math.sqrt(2.0); rootOf3 = Math.sqrt(3.0); } StaticBlock(String msg) { System.out.println(msg); } }
28

class SBDemo { public static void main(String args[]) { StaticBlock ob = new staticBlock("Inside Constructor"); System.out.println("Square root of 2 is " + StaticBlock.rootOf2); System.out.println("Square root of 3 is " + StaticBlock.rootOf3); } }

29

final Variables
It prevents modifying the value. It must be initialized. Choose all uppercase identifiers. Do not occupy memory on a perinstance basis. The keyword final can also be applied to methods.

final final final final final int int int int int FILE_NEW = 1; FILE_OPEN = 2; FILE_SAVE = 3; FILE_SAVEAS = 4; FILE_QUIT = 5;

30

Array Variables

Declaration
type var-name[ ]; //E.g: int arr[ ];

Memory Allocation
array-var = new type[size]; // arr=new int[5];

Types:
Single and Multi-Dimensional Array

Jagged Array- Different column sized array Alternative Array Declaration


int a[ ] = new int[5];
31

Example
class JArray { public static void main(String args[]) { int twoD[][] = new int[4][]; twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] = new int[3]; twoD[3] = new int[4]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<i+1; j++) {
32

twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<i+1; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } }

33

Example-2
// To find the length of array member. class Length { public static void main(String args[]) { int a1[] = new int[10]; int a2[] = {3, 5, 7, 1, 8, 99, 44, -10}; int a3[] = {4, 3, 2, 1}; System.out.println("length of a1 is " + a1.length); System.out.println("length of a2 is " + a2.length); System.out.println("length of a3 is " + a3.length); } }

34

Nested and Inner Classes

It is possible to define a class within another class; such classes are known as nested classes. There are two types of nested classes: static and non-static. A static nested class is one which has the static modifier applied. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do
35

class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
36

String Class
String is probably the most commonly used class in Javas class library. Every string that created is actually an object of type String. Even string constants are actually String objects.

String myString = "this is a test";

Java defines one operator for String objects: +.


String myString = "I" + " like " + "Java.";
37

Example
class StrDemo public static String strOb1 String strOb2 { void main(String args[]) { = "First String"; = "Second String";

String strOb3 = strOb1+" and "+strOb2; System.out.println(strOb1); System.out.println(strOb2); System.out.println(strOb3); } }


38

Some methods in String Class


boolean equals(String object) Compares two given string objects. int length( ) Gives the length of the given string. char charAt(int index) Gives the char at the given index.

39

class StringDemo2 { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1; System.out.println("Length of strOb1: " + strOb1.length()); System.out.println("Char at index 3 in strOb1:" + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println("strOb1 == strOb2"); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3"); else System.out.println("strOb1 != strOb3"); } }
40

Using Command-Line Arguments


A command-line argument is the information that directly follows the programs name on the command line when it is executed. They are stored as strings in the String array passed to main( ). Example:

class CommandLine { public static void main(String args[]) { for(int i=0; i<args.length; i++) System.out.println("args["+i+"]:"+ args[i]); } }

Try executing this program, as shown here:


java CommandLine this is a test 100 -1
41

Example
class CLDemo{ public static void main(String arg[]){ int a[]=new int[arg.length]; int sum=0; for(int i=0;i<arg.length;i++){ a[i]=Integer.parseInt(arg[i]); System.out.println(a[i]); sum=sum+a[i]; } System.out.println(The sum is : +sum); } }
42

S-ar putea să vă placă și