Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

611
LINES

< > BotCompany Repo | #3000030 // Contents of http://www.tutorialspoint.com/java/java_object_classes.htm

New Tinybrain snippet

1  
<!DOCTYPE html>
2  
<!--[if IE 8]><html class="ie ie8"> <![endif]-->
3  
<!--[if IE 9]><html class="ie ie9"> <![endif]-->
4  
<!--[if gt IE 9]><!-->	<html> <!--<![endif]-->
5  
<head>
6  
<!-- Basic -->
7  
<meta charset="utf-8">
8  
<title>Java - Object &amp; Classes</title>
9  
<meta name="description" content="Java Object &amp; Classes - Learning Java in simple and easy steps : A beginner's tutorial containing complete knowledge of Java Syntax Object Oriented Language, Methods, Overriding, Inheritance, Polymorphism, Interfaces, Packages, Collections, Networking, Multithreading, Generics, Multimedia, Serialization, GUI." />
10  
<meta name="keywords" content="Java, Tutorials, Learning, Beginners, Basics, Object Oriented Language, Methods, Overriding, Inheritance, Polymorphism, Interfaces, Packages, Collections, Networking, Multithreading, Generics, Multimedia, Serialization, GUI." />
11  
<base href="http://www.tutorialspoint.com/" />
12  
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
13  
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=yes">
14  
<meta name="author" content="tutorialspoint.com">
15  
<meta property="fb:app_id" content="471319149685276" />
16  
<script type="text/javascript" src="/theme/js/script-min-v4.js"></script>
17  
<link rel="stylesheet" href="/theme/css/style-min-v5.css">
18  
<!-- Head Libs -->
19  
<!--[if IE 8]>
20  
<link rel="stylesheet" type="text/css" href="/theme/css/ie8.css">
21  
<![endif]-->
22  
<!-- Front Page related changes -->
23  
<style>
24  
pre.prettyprint.tryit {background: #eee url(java/images/try-it.jpg) top right no-repeat !important}
25  
div.feature-box div.feature-box-icon, .col-md-3 .course-box, li.heading, div.footer-copyright { background: #eb4847 url(/images/pattern.png) repeat center center !important;}
26  
.sub-main-menu .sub-menuu div:hover, .sub-main-menu .viewall, header nav ul.nav-main li a:hover, button.btn-responsive-nav, header div.search button.btn-default { background: #eb4847 !important;}
27  
.submenu-item{ border-bottom: 2px solid #eb4847 !important; border-top: 2px solid #eb4847 !important }
28  
</style>
29  
<script>
30  
$(document).ready(function() {
31  
  $('input[name="q"]').keydown(function(event){
32  
    if(event.keyCode == 13) {
33  
      event.preventDefault();
34  
      return false;
35  
    }
36  
  });
37  
});
38  
</script>
39  
</head>
40  
<body onload="prettyPrint()">
41  
<div class="wrapLoader">
42  
   <div class="imgLoader">
43  
      <img  src="/images/loading-cg.gif" alt="" width="70" height="70" />
44  
   </div>
45  
</div>
46  
<header>
47  
   <div class="container">			
48  
      <h1 class="logo">
49  
      <a href="index.htm" title="tutorialspoint">
50  
      <img alt="tutorialspoint" src="/absoluteclasses/images/logo.png">
51  
      </a>
52  
      </h1>			
53  
      <div class="search" id="searchBar">
54  
         <form method="get" class="searchform" name="searchform" action="http://www.google.com/search" target="_blank">
55  
            <input type="hidden" name="sitesearch" value="www.tutorialspoint.com">
56  
            <div class="input-group">
57  
               <input type="text" class="form-control search" name="q" autocomplete="off" placeholder="Search your tutorials..." onfocus="if (this.value == 'Search your tutorials...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search your tutorials...';}">
58  
               <input value="FORID:11" name="cof" type="hidden">
59  
               <input type="hidden" name="ie" value="ISO-8859-1">
60  
               <span class="input-group-btn"> <button class="btn btn-default" type="submit" onclick="javascript:void(0);"><i class="icon icon-search"></i></button> </span>
61  
            </div>
62  
         </form>
63  
      </div>
64  
      <nav>
65  
         <ul class="nav nav-pills nav-top">
66  
            <li class="top-icons"> <a href="/free_online_whiteboard.htm"><i class="fa fa-desktop"></i> &nbsp;Whiteboard</a> </li>
67  
            <li class="top-icons"> <a href="/questions_and_answers.htm"><i class="fa fa-question"></i> &nbsp;Quizzes</a> </li>
68  
            <li> <a href="/shared-tutorials.php"><i class="icon icon-user"></i> &nbsp;Shared</a> </li>
69  
            <li> <a href="/articles/index.php"><i class="icon icon-file-text-o"></i> &nbsp;Articles</a> </li>
70  
            <li class="top-icons" style="display:none;"> <a href="job_search.php?search_string=jobs"><i class="fa fa-send"></i> &nbsp;Jobs</a> </li>
71  
72  
            <li class="top-icons" style="display:none;">
73  
              <ul class="social-icons">
74  
              <li class="facebook"><a href="https://www.facebook.com/tutorialspointindia" target="_blank" data-placement="bottom" title="tutorialspoint @ Facebook">Facebook</a></li>
75  
              <li class="googleplus"><a href="https://plus.google.com/u/0/116678774017490391259/posts" target="_blank" data-placement="bottom" title="tutorialspoint @ Google+">Google+</a></li>
76  
              <li class="twitter"><a href="http://www.twitter.com/tutorialspoint" target="_blank" data-placement="bottom" title="tutorialspoint @ Twitter">Twitter</a></li>
77  
              <li class="linkedin"><a href="http://www.linkedin.com/company/tutorialspoint" target="_blank" data-placement="bottom" title="tutorialspoint @ Linkedin">Linkedin</a></li>
78  
              <li class="rss"><a href="http://feeds.feedburner.com/SharedTutorials" target="_blank" data-placement="bottom" title="tutorialspoint RSS">RSS</a></li>
79  
              </ul>
80  
           </li>
81  
         </ul>
82  
      </nav>
83  
         <!-- search code here  --> 
84  
      <button class="btn btn-responsive-nav btn-inverse" data-toggle="collapse" data-target=".nav-main-collapse" id="pull"> <i class="icon icon-bars"></i> </button>
85  
   </div>
86  
   <div class="navbar nav-main">
87  
      <div class="container">
88  
         <nav class="nav-main mega-menu">
89  
            <ul class="nav nav-pills nav-main" id="mainMenu">
90  
               <li class="dropdown no-sub-menu"> <a class="dropdown" href="index.htm"><i class="icon icon-home"></i> Home</a> </li>   
91  
               <li class="dropdown" id="liTL"><a class="dropdown tut-lib" href="javascript:void(0);"> Tutorials Library  <i class="fa-caret-down"></i> </a></li>
92  
               <li class="dropdown" id="liCG"><a class="dropdown" href="javascript:void(0);"><i class="fa-code"></i> Coding Ground <i class="fa-caret-down"></i> </a> </li>
93  
               <li class="dropdown no-sub-menu"><a class="dropdown tut-plus" href="/absoluteclasses/upcomingclasses.htm">Absolute Classes</a>
94  
               </li>
95  
            </ul>
96  
         </nav>
97  
         <div class="submenu-item sub-main-menu" id="top-sub-menu"></div>
98  
      </div>
99  
   </div>	
100  
</header>
101  
<div style="clear:both;"></div>
102  
<div role="main" class="main">
103  
<div class="container">
104  
<div class="row">
105  
<div class="col-md-2">
106  
<aside class="sidebar">
107  
  <div class="mini-logo">
108  
<img src="/java/images/java-mini-logo.jpg" alt="Java Tutorial" />
109  
</div>
110  
<ul class="nav nav-list primary left-menu" >
111  
<li class="heading">Java Tutorial</li>
112  
<li><a target="_top" href="/java/index.htm">Java - Home</a></li>
113  
<li><a target="_top" href="/java/java_overview.htm">Java - Overview</a></li>
114  
<li><a target="_top" href="/java/java_environment_setup.htm">Java - Environment Setup</a></li>
115  
<li><a target="_top" href="/java/java_basic_syntax.htm">Java - Basic Syntax</a></li>
116  
<li><a target="_top" href="/java/java_object_classes.htm">Java - Object &amp; Classes</a></li>
117  
<li><a target="_top" href="/java/java_basic_datatypes.htm">Java - Basic Datatypes</a></li>
118  
<li><a target="_top" href="/java/java_variable_types.htm">Java - Variable Types</a></li>
119  
<li><a target="_top" href="/java/java_modifier_types.htm">Java - Modifier Types</a></li>
120  
<li><a target="_top" href="/java/java_basic_operators.htm">Java - Basic Operators</a></li>
121  
<li><a target="_top" href="/java/java_loop_control.htm">Java - Loop Control</a></li>
122  
<li><a target="_top" href="/java/java_decision_making.htm">Java - Decision Making</a></li>
123  
<li><a target="_top" href="/java/java_numbers.htm">Java - Numbers</a></li>
124  
<li><a target="_top" href="/java/java_characters.htm">Java - Characters</a></li>
125  
<li><a target="_top" href="/java/java_strings.htm">Java - Strings</a></li>
126  
<li><a target="_top" href="/java/java_arrays.htm">Java - Arrays</a></li>
127  
<li><a target="_top" href="/java/java_date_time.htm">Java - Date &amp; Time</a></li>
128  
<li><a target="_top" href="/java/java_regular_expressions.htm">Java - Regular Expressions</a></li>
129  
<li><a target="_top" href="/java/java_methods.htm">Java - Methods</a></li>
130  
<li><a target="_top" href="/java/java_files_io.htm">Java - Files and I/O</a></li>
131  
<li><a target="_top" href="/java/java_exceptions.htm">Java - Exceptions</a></li>
132  
<li><a target="_top" href="/java/java_innerclasses.htm">Java - Inner classes</a></li>
133  
</ul>
134  
<ul class="nav nav-list primary left-menu" >
135  
<li class="heading">Java Object Oriented</li>
136  
<li><a target="_top" href="/java/java_inheritance.htm">Java - Inheritance</a></li>
137  
<li><a target="_top" href="/java/java_overriding.htm">Java - Overriding</a></li>
138  
<li><a target="_top" href="/java/java_polymorphism.htm">Java - Polymorphism</a></li>
139  
<li><a target="_top" href="/java/java_abstraction.htm">Java - Abstraction</a></li>
140  
<li><a target="_top" href="/java/java_encapsulation.htm">Java - Encapsulation</a></li>
141  
<li><a target="_top" href="/java/java_interfaces.htm">Java - Interfaces</a></li>
142  
<li><a target="_top" href="/java/java_packages.htm">Java - Packages</a></li>
143  
</ul>
144  
<ul class="nav nav-list primary left-menu" >
145  
<li class="heading">Java Advanced</li>
146  
<li><a target="_top" href="/java/java_data_structures.htm">Java - Data Structures</a></li>
147  
<li><a target="_top" href="/java/java_collections.htm">Java - Collections</a></li>
148  
<li><a target="_top" href="/java/java_generics.htm">Java - Generics</a></li>
149  
<li><a target="_top" href="/java/java_serialization.htm">Java - Serialization</a></li>
150  
<li><a target="_top" href="/java/java_networking.htm">Java - Networking</a></li>
151  
<li><a target="_top" href="/java/java_sending_email.htm">Java - Sending Email</a></li>
152  
<li><a target="_top" href="/java/java_multithreading.htm">Java - Multithreading</a></li>
153  
<li><a target="_top" href="/java/java_applet_basics.htm">Java - Applet Basics</a></li>
154  
<li><a target="_top" href="/java/java_documentation.htm">Java - Documentation</a></li>
155  
</ul>
156  
<ul class="nav nav-list primary left-menu" >
157  
<li class="heading">Java Interview Questions</li>
158  
<li><a target="_top" href="/java/java_interview_questions.htm">Java - Interview Questions</a></li>
159  
</ul>
160  
<ul class="nav nav-list primary left-menu" >
161  
<li class="heading">Java Useful Resources</li>
162  
<li><a target="_top" href="/java/java_quick_guide.htm">Java - Quick Guide</a></li>
163  
<li><a target="_top" href="/java/java_useful_resources.htm">Java - Useful Resources</a></li>
164  
<li><a target="_top" href="/java/java_discussion.htm">Java - Discussion</a></li>
165  
<li><a target="_top" href="/javaexamples/index.htm">Java - Examples</a></li>
166  
</ul>
167  
<ul class="nav nav-list primary push-bottom left-menu special">
168  
<li class="sreading">Selected Reading</li>
169  
<li><a target="_top" href="/developers_best_practices/index.htm">Developer's Best Practices</a></li>
170  
<li><a target="_top" href="/questions_and_answers.htm">Questions and Answers</a></li>
171  
<li><a target="_top" href="/effective_resume_writing.htm">Effective Resume Writing</a></li>
172  
<li><a target="_top" href="/hr_interview_questions/index.htm">HR Interview Questions</a></li>
173  
<li><a target="_top" href="/computer_glossary.htm">Computer Glossary</a></li>
174  
<li><a target="_top" href="/computer_whoiswho.htm">Who is Who</a></li>
175  
</ul>
176  
</aside>
177  
</div>
178  
<!-- PRINTING STARTS HERE -->
179  
<div class="row">
180  
<div class="content">
181  
<div class="col-md-7 middle-col">
182  
<h1>Java - Object &amp; Classes</h1>
183  
<div class="topgooglead">
184  
<hr />
185  
<div style="padding-bottom:5px;padding-left:10px;">Advertisements</div>
186  
<script type="text/javascript"><!--
187  
google_ad_client = "pub-7133395778201029";
188  
google_ad_width = 468;
189  
google_ad_height = 60;
190  
google_ad_format = "468x60_as";
191  
google_ad_type = "image";
192  
google_ad_channel = "";
193  
//--></script>
194  
<script type="text/javascript"
195  
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
196  
</script>
197  
</div>
198  
<hr />
199  
<div class="pre-btn">
200  
<a href="/java/java_basic_syntax.htm"><i class="icon icon-arrow-circle-o-left big-font"></i> Previous Page</a>
201  
</div>
202  
<div class="nxt-btn">
203  
<a href="/java/java_basic_datatypes.htm">Next Page <i class="icon icon-arrow-circle-o-right big-font"></i>&nbsp;</a>
204  
</div>
205  
<div class="clearer"></div>
206  
<hr />
207  
<p>Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:</p>
208  
<ul class="list">
209  
<li>Polymorphism</li>
210  
<li>Inheritance</li>
211  
<li>Encapsulation</li>
212  
<li>Abstraction</li>
213  
<li>Classes</li>
214  
<li>Objects</li>
215  
<li>Instance</li>
216  
<li>Method</li>
217  
<li>Message Parsing</li>
218  
</ul>
219  
<p>In this chapter, we will look into the concepts Classes and Objects.</p>
220  
<ul class="list">
221  
<li><p><b>Object -</b> Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. </p></li>
222  
<li><p><b>Class -</b> A class can be defined as a template/blue print that describes the behaviors/states that object of its type support.</p></li>
223  
</ul>
224  
<h2>Objects in Java:</h2>
225  
<p>Let us now look deep into what are objects. If we consider the real-world we can find many objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.</p>
226  
<p>If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging, running</p>
227  
<p>If you compare the software object with a real world object, they have very similar characteristics.</p>
228  
<p>Software objects also have a state and behavior. A software object's state is stored in fields and behavior is shown via methods.</p>
229  
<p>So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.</p>
230  
<h2>Classes in Java:</h2>
231  
<p>A class is a blue print from which individual objects are created.</p>
232  
<p>A sample of a class is given below:</p>
233  
<pre class="prettyprint notranslate">
234  
public class Dog{
235  
   String breed;
236  
   int ageC
237  
   String color;
238  
239  
   void barking(){
240  
   }
241  
   
242  
   void hungry(){
243  
   }
244  
   
245  
   void sleeping(){
246  
   }
247  
}
248  
</pre>
249  
<p>A class can contain any of the following variable types.</p>
250  
<ul class="list">
251  
<li><p><b>Local variables: </b>Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.</p></li>
252  
<li><p><b>Instance variables: </b>Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.</p></li>
253  
<li><p><b>Class variables: </b>Class variables are variables declared with in a class, outside any method, with the static keyword.</p></li>
254  
</ul>
255  
<p>A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods.</p>
256  
<p>Below mentioned are some of the important topics that need to be discussed when looking into classes of the Java Language.</p>
257  
<h2>Constructors:</h2>
258  
<p>When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default constructor for that class.</p>
259  
<p>Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.</p>
260  
<p>Example of a constructor is given below:</p>
261  
<pre class="prettyprint notranslate">
262  
public class Puppy{
263  
   public Puppy(){
264  
   }
265  
266  
   public Puppy(String name){
267  
      // This constructor has one parameter, <i>name</i>.
268  
   }
269  
}
270  
</pre>
271  
272  
273  
<p></p>
274  
<p>Java also supports <a href="/java/java_using_singleton.htm">Singleton Classes</a> where you would be able to create only one instance of a class.</p>
275  
<p><b>Note: </b>We have two different types of constructors we are going to discuss constructors in detail in coming chapters.</p>
276  
<h2>Creating an Object:</h2>
277  
<p>As mentioned previously, a class provides the blueprints for objects. So basically an object is created from a class. In Java, the new key word is used to create new objects. </p>
278  
<p>There are three steps when creating an object from a class:</p>
279  
<ul class="list">
280  
<li><p><b>Declaration: </b>A variable declaration with a variable name with an object type.</p></li>
281  
<li><p><b>Instantiation: </b>The 'new' key word is used to create the object.</p></li>
282  
<li><p><b>Initialization: </b>The 'new' keyword is followed by a call to a constructor. This call initializes the new object.</p></li>
283  
</ul>
284  
<p>Example of creating an object is given below:</p>
285  
<pre class="prettyprint notranslate tryit">
286  
public class Puppy{
287  
288  
   public Puppy(String name){
289  
      // This constructor has one parameter, <i>name</i>.
290  
      System.out.println("Passed Name is :" + name ); 
291  
   }
292  
   
293  
   public static void main(String []args){
294  
      // Following statement would create an object myPuppy
295  
      Puppy myPuppy = new Puppy( "tommy" );
296  
   }
297  
}
298  
</pre>
299  
<p>If we compile and run the above program, then it would produce the following result:</p>
300  
<pre class="prettyprint notranslate">
301  
Passed Name is :tommy
302  
</pre>
303  
<h2>Accessing Instance Variables and Methods:</h2>
304  
<p>Instance variables and methods are accessed via created objects. To access an instance variable the fully qualified path should be as follows:</p>
305  
<pre class="prettyprint notranslate">
306  
/* First create an object */
307  
ObjectReference = new Constructor();
308  
309  
/* Now call a variable as follows */
310  
ObjectReference.variableName;
311  
312  
/* Now you can call a class method as follows */
313  
ObjectReference.MethodName();
314  
</pre>
315  
<h2>Example:</h2>
316  
<p>This example explains how to access instance variables and methods of a class:</p>
317  
<pre class="prettyprint notranslate tryit">
318  
public class Puppy{
319  
   
320  
   int puppyAge;
321  
322  
   public Puppy(String name){
323  
      // This constructor has one parameter, <i>name</i>.
324  
      System.out.println("Name chosen is :" + name ); 
325  
   }
326  
   
327  
   public void setAge( int age ){
328  
       puppyAge = age;
329  
   }
330  
331  
   public int getAge( ){
332  
       System.out.println("Puppy's age is :" + puppyAge ); 
333  
       return puppyAge;
334  
   }
335  
   
336  
   public static void main(String []args){
337  
      /* Object creation */
338  
      Puppy myPuppy = new Puppy( "tommy" );
339  
340  
      /* Call class method to set puppy's age */
341  
      myPuppy.setAge( 2 );
342  
343  
      /* Call another class method to get puppy's age */
344  
      myPuppy.getAge( );
345  
346  
      /* You can access instance variable as follows as well */
347  
      System.out.println("Variable Value :" + myPuppy.puppyAge ); 
348  
   }
349  
}
350  
</pre>
351  
<p>If we compile and run the above program, then it would produce the following result:</p>
352  
<pre class="prettyprint notranslate">
353  
Name chosen is :tommy
354  
Puppy's age is :2
355  
Variable Value :2
356  
</pre>
357  
<h2>Source file declaration rules:</h2>
358  
<p>As the last part of this section let's now look into the source file declaration rules. These rules are essential when declaring classes, <i>import</i> statements and <i>package</i> statements in a source file.</p>
359  
<ul class="list">
360  
<li><p>There can be only one public class per source file.</p></li>
361  
<li><p>A source file can have multiple non public classes.</p></li>
362  
<li><p>The public class name should be the name of the source file as well which should be appended by <b>.java</b> at the end. For example: the class name is <i>public class Employee{}</i> then the source file should be as Employee.java.</p></li>
363  
<li><p>If the class is defined inside a package, then the package statement should be the first statement in the source file.</p></li>
364  
<li><p>If import statements are present then they must be written between the package statement and the class declaration. If there are no package statements then the import statement should be the first line in the source file. </p></li>
365  
<li><p>Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.</p></li>
366  
</ul>
367  
<p>Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. we will be explaining about all these in the access modifiers chapter.</p>
368  
<p>Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.</p>
369  
<h2>Java Package:</h2>
370  
<p>In simple, it is a way of categorizing the classes and interfaces. When developing applications in Java,  hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.</p>
371  
<h2>Import statements:</h2>
372  
<p>In Java if a fully qualified name, which includes the package and the class name, is given then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.</p>
373  
<p>For example, the following line would ask compiler to load all the classes available in directory java_installation/java/io :</p>
374  
<pre class="prettyprint notranslate">
375  
import java.io.*;
376  
</pre>
377  
<h2>A Simple Case Study</h2>
378  
<p>For our case study, we will be creating two classes. They are Employee and EmployeeTest.</p>
379  
<p>First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java.</p>
380  
<p>The Employee class has four instance variables name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.</p>
381  
<pre class="prettyprint notranslate" id="employee">
382  
import java.io.*;
383  
384  
public class Employee{
385  
386  
   String name;
387  
   int age;
388  
   String designation;
389  
   double salary;
390  
	
391  
   // This is the constructor of the class Employee
392  
   public Employee(String name){
393  
      this.name = name;
394  
   }
395  
   // Assign the age of the Employee  to the variable age.
396  
   public void empAge(int empAge){
397  
      age =  empAge;
398  
   }
399  
   /* Assign the designation to the variable designation.*/
400  
   public void empDesignation(String empDesig){
401  
      designation = empDesig;
402  
   }
403  
   /* Assign the salary to the variable	salary.*/
404  
   public void empSalary(double empSalary){
405  
      salary = empSalary;
406  
   }
407  
   /* Print the Employee details */
408  
   public void printEmployee(){
409  
      System.out.println("Name:"+ name );
410  
      System.out.println("Age:" + age );
411  
      System.out.println("Designation:" + designation );
412  
      System.out.println("Salary:" + salary);
413  
   }
414  
}
415  
</pre>
416  
<p>As mentioned previously in this tutorial, processing starts from the main method. Therefore in-order for us to run this Employee class there should be main method and objects should be created. We will be creating a separate class for these tasks.</p>
417  
<p>Given below is the <i>EmployeeTest</i> class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.</p>
418  
<p>Save the following code in EmployeeTest.java file</p>
419  
<pre class="prettyprint notranslate tryit" title="employee">
420  
import java.io.*;
421  
422  
public class EmployeeTest{
423  
424  
   public static void main(String args[]){
425  
      /* Create two objects using constructor */
426  
      Employee empOne = new Employee("James Smith");
427  
      Employee empTwo = new Employee("Mary Anne");
428  
429  
      // Invoking methods for each object created
430  
      empOne.empAge(26);
431  
      empOne.empDesignation("Senior Software Engineer");
432  
      empOne.empSalary(1000);
433  
      empOne.printEmployee();
434  
435  
      empTwo.empAge(21);
436  
      empTwo.empDesignation("Software Engineer");
437  
      empTwo.empSalary(500);
438  
      empTwo.printEmployee();
439  
   }
440  
}
441  
</pre>
442  
<p>Now, compile both the classes and then run <i>EmployeeTest</i> to see the result as follows:</p>
443  
<pre class="prettyprint notranslate">
444  
C:\&gt; javac Employee.java
445  
C:\&gt; javac EmployeeTest.java
446  
C:\&gt; java EmployeeTest
447  
Name:James Smith
448  
Age:26
449  
Designation:Senior Software Engineer
450  
Salary:1000.0
451  
Name:Mary Anne
452  
Age:21
453  
Designation:Software Engineer
454  
Salary:500.0
455  
</pre>
456  
<h2>What is Next?</h2>
457  
<p>Next session will discuss basic data types in Java and how they can be used when developing Java applications.</p>
458  
<hr />
459  
<div class="pre-btn">
460  
<a href="/java/java_basic_syntax.htm"><i class="icon icon-arrow-circle-o-left big-font"></i> Previous Page</a>
461  
</div>
462  
<div class="print-btn center">
463  
<a href="/cgi-bin/printpage.cgi" target="_blank"><i class="icon icon-print big-font"></i> Print</a>
464  
</div>
465  
<div class="pdf-btn">
466  
<a href="/java/pdf/java_object_classes.pdf" title="Java - Object &amp; Classes" target="_blank"><i class="icon icon-file-pdf-o big-font"></i> PDF</a>
467  
</div>
468  
<div class="nxt-btn">
469  
<a href="/java/java_basic_datatypes.htm">Next Page <i class="icon icon-arrow-circle-o-right big-font"></i>&nbsp;</a>
470  
</div>
471  
<hr />
472  
<!-- PRINTING ENDS HERE -->
473  
<div class="bottomgooglead">
474  
<div class="bottomadtag">Advertisements</div>
475  
<script type="text/javascript"><!--
476  
var width = 580;
477  
var height = 400;
478  
var format = "580x400_as";
479  
if( window.innerWidth < 468 ){
480  
   width = 300;
481  
   height = 250;
482  
   format = "300x250_as";
483  
}
484  
google_ad_client = "pub-7133395778201029";
485  
google_ad_width = width;
486  
google_ad_height = height;
487  
google_ad_format = format;
488  
google_ad_type = "image";
489  
google_ad_channel ="";
490  
//--></script>
491  
<script type="text/javascript"
492  
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
493  
</script>
494  
</div>
495  
</div>
496  
</div>
497  
<div class="row">
498  
<div class="col-md-3" id="rightbar">
499  
<div class="simple-ad">
500  
<a href="javascript:void(0)" onclick="var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313);window.open('http://www.facebook.com/sharer.php?u=' + 'http://www.tutorialspoint.com/java/java_object_classes.htm','sharer','toolbar=0,status=0,width=626,height=456,top='+sTop+',left='+sLeft);return false;">
501  
<img src="/images/facebookIcon.jpg" alt="img" />
502  
</a>
503  
<a  href="javascript:void(0)" onclick="var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313);window.open('http://twitter.com/share?url=' + 'http://www.tutorialspoint.com/java/java_object_classes.htm','sharer','toolbar=0,status=0,width=626,height=456,top='+sTop+',left='+sLeft);return false;">
504  
<img src="/images/twitterIcon.jpg" alt="img" />
505  
</a>
506  
<a  href="javascript:void(0)" onclick="var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313);window.open('https://www.linkedin.com/cws/share?url=' + 'http://www.tutorialspoint.com/java/java_object_classes.htm&amp;title='+ document.title,'sharer','toolbar=0,status=0,width=626,height=456,top='+sTop+',left='+sLeft);return false;">
507  
<img src="/images/linkedinIcon.jpg" alt="img" />
508  
</a>
509  
<a  href="javascript:void(0)" onclick="var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313);window.open('https://plus.google.com/share?url=http://www.tutorialspoint.com/java/java_object_classes.htm','sharer','toolbar=0,status=0,width=626,height=456,top='+sTop+',left='+sLeft);return false;">
510  
<img src="/images/googlePlusIcon.jpg" alt="img" />
511  
</a>
512  
<a  href="javascript:void(0)" onclick="var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313);window.open('http://www.stumbleupon.com/submit?url=http://www.tutorialspoint.com/java/java_object_classes.htm&amp;title='+ document.title,'sharer','toolbar=0,status=0,width=626,height=456,top='+sTop+',left='+sLeft);return false;">
513  
<img src="/images/StumbleUponIcon.jpg" alt="img" />
514  
</a>
515  
<a  href="javascript:void(0)" onclick="var sTop = window.screen.height/2-(218); var sLeft = window.screen.width/2-(313);window.open('http://reddit.com/submit?url=http://www.tutorialspoint.com/java/java_object_classes.htm&amp;title='+ document.title,'sharer','toolbar=0,status=0,width=626,height=656,top='+sTop+',left='+sLeft);return false;">
516  
<img src="/images/reddit.jpg" alt="img" />
517  
</a>
518  
</div>
519  
<div class="rightgooglead">
520  
<script type="text/javascript"><!--
521  
google_ad_client = "pub-7133395778201029";
522  
google_ad_width = 300;
523  
google_ad_height = 250;
524  
google_ad_format = "300x250_as";
525  
google_ad_type = "image";
526  
google_ad_channel ="";
527  
//--></script>
528  
<script type="text/javascript"
529  
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
530  
</script>
531  
</div>
532  
<div class="rightgooglead">
533  
<script type="text/javascript"><!--
534  
google_ad_client = "pub-7133395778201029";
535  
google_ad_width = 300;
536  
google_ad_height = 600;
537  
google_ad_format = "300x600_as";
538  
google_ad_type = "image";
539  
google_ad_channel ="";
540  
//--></script>
541  
<script type="text/javascript"
542  
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
543  
</script>
544  
</div>
545  
<div class="rightgooglead">
546  
<script type="text/javascript"><!--
547  
google_ad_client = "ca-pub-2537027957187252";
548  
/* Right Side Ad */
549  
google_ad_slot = "right_side_ad";
550  
google_ad_width = 300;
551  
google_ad_height = 250;
552  
//-->
553  
</script>
554  
<script type="text/javascript"
555  
src="//pagead2.googlesyndication.com/pagead/show_ads.js">
556  
</script>
557  
</div>
558  
</div>
559  
</div>
560  
</div>
561  
</div>
562  
</div>
563  
564  
<div class="footer-copyright">
565  
<div class="container">
566  
<div class="row">
567  
<div class="col-md-1">
568  
<a href="index.htm" class="logo"> <img alt="Tutorials Point" class="img-responsive" src="/scripts/img/logo-footer.png"> </a>
569  
</div>
570  
<div class="col-md-4 col-sm-12 col-xs-12">
571  
   <nav id="sub-menu">
572  
      <ul>
573  
         <li><a href="/about/tutorials_writing.htm">Write for us</a></li>
574  
         <li><a href="/about/faq.htm">FAQ's</a></li>
575  
         <li><a href="/about/about_helping.htm">Helping</a></li>
576  
         <li><a href="/about/contact_us.htm">Contact</a></li>
577  
      </ul>
578  
   </nav>
579  
</div>
580  
<div class="col-md-3 col-sm-12 col-xs-12">
581  
<p>&copy; Copyright 2015. All Rights Reserved.</p>
582  
</div>
583  
<div class="col-md-4 col-sm-12 col-xs-12">
584  
   <div class="news-group">
585  
      <input type="text" class="form-control-foot search" name="textemail" id="textemail" autocomplete="off" placeholder="Enter email for newsletter" onfocus="if (this.value == 'Enter email for newsletter...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter email for newsletter...';}">
586  
      <span class="input-group-btn"> <button class="btn btn-default btn-footer" id="btnemail" type="submit" onclick="javascript:void(0);">go</button> </span>
587  
      <div id="newsresponse"></div>
588  
   </div>
589  
</div>
590  
</div>
591  
</div>
592  
</div>
593  
</div>
594  
<!-- Libs -->
595  
<script type="text/javascript" src="/theme/js/custom-min.js"></script>
596  
<script src="http://www.google-analytics.com/urchin.js">
597  
</script>
598  
<script type="text/javascript">
599  
_uacct = "UA-232293-6";
600  
urchinTracker();
601  
$('.pg-icon').click(function(){
602  
   $('.wrapLoader').show();
603  
});
604  
</script>
605  
<script type="text/javascript" src="/theme/js/jquery.colorbox-min.js"></script>
606  
<script type="text/javascript">
607  
   var tryit = new $.TryIt('java/try_java.php');
608  
   tryit.compile();
609  
</script></div>
610  
</body>
611  
</html>

download  show line numbers   

Snippet is not live.

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #3000030
Snippet name: Contents of http://www.tutorialspoint.com/java/java_object_classes.htm
Eternal ID of this version: #3000030/1
Text MD5: 356ccfd374e4e286b04710d37c8f08b2
Author: someone
Category:
Type: New Tinybrain snippet
Gummipassword: url-loader
Uploaded from IP: 176.0.118.225
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-08-30 18:09:01
Source code size: 31050 bytes / 611 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 2222 / 989
Referenced in: [show references]