Vous êtes sur la page 1sur 7

2.

4 Objects and Classes Introduction Java is a true object-oriented language and therefore the underlying structure of all Java programs in classes. Anything we wish to represent in a Java program must be encapsulated in a class that defines the state and behavior of the basic program components known as objects. Class provides a convenient method for packing together a group of logically related data items and functions that work on them. In java, the data items are called fields and the functions are called methods. Calling specific methods in an object is described as sending the object a message. Defining a Class The keyword class is used to define a class of objects. The general syntax for declaring a class is:
class classname { //field declaration datatype variables1; datatype variables2; . datatype variablesn; //methods declaration return-type method1(parameter-list) { //body of method } }
/* A program that uses the Box Class. * Call this file BoxDemo1.java */ class Box { double width; double height; double depth; } //This class declares an object of type Box public class BoxDemo1 { public static void main(String args[]) { Box mybox = new Box(); double vol; //assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; //compute volume of box vol=mybox.width*mybox.height*mybox.depth; System.out.println("Volume is "+vol); } }

[Type text]

Page 1

Creating Object Object in Java are created using the new operator. The new operator creates an object of the specified class and returns a reference to that objects. Box mybox = new Box(); This statement combines the two steps just described. It can be rewritten as Box myBox; //declare reference to object mybox = new Box(); //allocate a Box object Adding a Method to the Box Class
//This program include a method inside the box class class Box{ double width; double height; double depth; //displaying volume of a box void volume(){ System.out.print("Volume is "); System.out.println(width*height*depth); } } public class BoxDemo2 { public static void main(String args[]){ Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; //displaying volume mybox.volume(); } }

Returning a Value
//Now, volume() returns the volume of a box class Box{ double width; double height; double depth; //compute and return volume double volume(){ return width*height*depth; } } public class BoxDemo3 { public static void main(String args[]){ Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; //get volume vol=mybox.volume(); System.out.println("Volume is "+vol); } }

[Type text]

Page 2

Adding a Method that takes parameters Parameters allow a method to be generalized. That is, a parameterized method can operate on a variety of data and/or be used in a number of slightly different situations.
//This program uses a parameterized method class Box { double width; double height; double depth; //compute and return volume double volume(){ return width*height*depth; } //sets dimensions of box void setDim(double w,double h,double d){ width=w; height=h; depth=d; } } public class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; //initialize each box mybox1.setDim(10,20,15); mybox2.setDim(3,6,9); //get volume of the first box vol=mybox1.volume(); System.out.println("Volume is "+vol); //get volume of the second box vol=mybox2.volume(); System.out.println("Volume is "+vol); } }

Constructors Java supports a special type of methods, called a constructor that enables an object to initialize itself when it is created. Constructors have the same name as the class itself. Secondly, they do not specify a return type, not even void. This is because they return the instance of the class itself.

[Type text]

Page 3

// Here, Box uses a constructor to initialize the dimensions of a box class Box{ double width; double height; double depth; //This is the constructor for box Box(){ System.out.println("Costructing Box"); width=10; height=10; depth=10; } double volume(){ return width*height*depth; } } public class BoxDemo5 { public static void main(String args[]){ //declare, allocate, and initialize Box Objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; vol=mybox1.volume(); System.out.println("Volume is "+vol); vol=mybox2.volume(); System.out.println("Volume is "+vol); } }

Parameterized Constructors
/*Here, Box uses a parameterized constructor to initialize the dimension of a box */ class Box{ double width; double height; double depth; //This is the constructor for box Box(double w,double h,double d){ width=w; height=h; depth=d; } double volume(){ return width*height*depth; } } public class BoxDemo5 { public static void main(String args[]){ Box mybox1 = new Box(10,20,15); Box mybox2 = new Box(3,6,9); double vol; vol=mybox1.volume(); System.out.println("Volume is "+vol); vol=mybox2.volume(); System.out.println("Volume is "+vol); } }

[Type text]

Page 4

static Fields and Methods Let us assume that we want to define a member that is common to all objects and accessed without using a particular object. That is, the member belongs to the class as a whole rather than the objects created from the class. Such members can be defined as follows: static int count; static int max(int x,int y); The following important points should be remembered about the keyword static: All statements containing the static keyword are executed first. Member variable declared as static are global variables. That is, when objects of that class are declared, no copy of the static member variable is made. Instead, all instances (objects) of the class share the same static variable. Member methods declared as static: Can only call other static methods directly, Can only access static data directly and Cannot use keywords this and super.
//Defining and using static members class Mathoperation { static double mul(double x, double y) { return x*y; } static double divide(double x,double y) { return x/y; } } //Class containing main method public class MathApplication { public static void main(String args[]) { double a=Mathoperation.mul(4.15, 5.35); double b=Mathoperation.divide(a,2.0); System.out.println("b="+b); } }

Methods Overloading In Java, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. Method overloading is used when objects are required to perform similar tasks but using different input parameters. Example: double sum(double x, double y){ double sum(double x){ }
[Type text]

Page 5

//Method overloading public class animal { public void eat() { System.out.println("All animal eat"); } public void eat(int x) { System.out.println("Whale eat "+x+" tons of food"); } public void eat(String str) { System.out.println("Parrot eat "+str); } public static void main(String strs[]) { animal a=new animal(); a.eat(); a.eat(5); a.eat("grains"); } }

Packages Packages are Javas way of grouping a variety of classes and/or interfaces together. The grouping is usually done according to functionality. In fact, packages act as containers for classes. By organizing our classes into packages we achieve the following benefits: The classes contained in the packages of the other programs can be easily reused. In Packages, classes can be unique compared with classes in other packages. That is, two classes in two different packages can have same name. They may be referred by their fully qualified name, comprising the package name and the class name. Packages provide a way to hide classes thus preventing other programs or packages from accessing classes that are meant for internal use only. Packages also provide a way for separating design from coding. First we can design classes and decide their relationships, and then we can implement the Java code needed for the methods. It is possible to change the implementation of any method without affecting the rest of the design. Using System Packages There are two way of accessing the classes stored in a package. import packagename.classname; or import packagename.* double y= java.lang.Math.sqrt(x); package name
[Type text]

class name

method name
Page 6

Java Packages are classified into two types 1. Java API Packages 2. Defined Packages Java API Packages Package Name Contents java.lang Language support classes. These are classes that Java compiler itself uses and therefore they are automatically imported. They include classes for primitive types, strings, math functions, threads and exceptions. java.util Language utility classes such as vectors, hash tables, random numbers, date etc. java.io Input/output support classes. They provide facilities for the input and output of data. java.awt Set of classes for implementing graphical user interface. They include classes for windows, buttons, lists, menus and so on. java.net Classes for networking. They include classes for communicating with local computers as well as with internet servers. java.applet Classes for creating and implementing applets.

[Type text]

Page 7

Vous aimerez peut-être aussi