A simple class
By: aathishankaran Printer Friendly Format
A simple class
Here is a class called BOX that defines three instance
variables: width, height, and depth. Currently, Box does not contain any methods
(but some will be added soon).
class Box {
double width;
double height;
double depth;
}
As stated, a class defines a new type of data. In this case, the new data
type is called Box. You will use this name to declare objects of type Box. It is
important to remember that a class declaration only creates a template; it does
not create an actual object. Thus, the preceding code does not cause any objects
of type Box to come into existence.
To actually create a Box object, you will use a statement like the
following:
Box mybox = new Box() ;
After this statement executes, mybox will be an instance of Box. Thus, it
will have “physical†reality.
For the moment, don’t worry about the details of this statement.
Again, each time you create an instance of a class, you are creating an
object that contains its own copy of each instance variable defined by the
class. Thus, every Box object will contain its own copies of the instance
variables width, height, and depth. To access these object you will use the dot
(.) operator. The dot operator links the name of the object with the name of an
instance variable. For example, to assign the width variable of mybox the value
100, you would use the following statement:
Mybox.width =
100;
This statement
tells the compiler to assign the copy of width that is contained within the
mybox object the value of 100. in general, you use the dot operator to access
both the instance variables and the methods within an object.
Here is a complete program that uses the Box class:
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main (String args[]) {
Box mybox = new Box ();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ( “volume is†+ vol);
}
}
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java