{"id":409,"date":"2021-01-04T17:52:43","date_gmt":"2021-01-04T17:52:43","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/?page_id=409"},"modified":"2021-01-04T17:56:27","modified_gmt":"2021-01-04T17:56:27","slug":"class-variables-methods","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/class-variables-methods\/","title":{"rendered":"Class Variables &#038; Methods"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a2d0c8f3a636\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a2d0c8f3a636\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/class-variables-methods\/#Class_vs_Instance_Variables\" >Class vs. Instance Variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/class-variables-methods\/#Usage\" >Usage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/class-variables-methods\/#Initialization\" >Initialization<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/class-variables-methods\/#Static_Initializers\" >Static Initializers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/course-topics\/classes-objects\/class-variables-methods\/#Initialization_Blocks\" >Initialization Blocks<\/a><\/li><\/ul><\/nav><\/div>\n\n<p class=\"wp-block-paragraph\">So far, we&#8217;ve looked at <em>instance variables and methods<\/em> &#8212; that is, variables and methods associated with a specific instance of a class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, it is possible to associate both variables and methods with the class itself.&nbsp; These are known as <em>class variables and class methods<\/em>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Class_vs_Instance_Variables\"><\/span>Class vs. Instance Variables<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Consider the class&nbsp;<strong>BankAccount<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\nclass BankAccount\n{\n   \/\/ Instance methods\n   double deposit(double amount)\n   {\n      m_balance += amount;\n      return m_balance;\n   }\n   \/\/ Instance variables\n   String m_holder;\n   double m_balance;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">For each&nbsp;<em>instance<\/em>&nbsp;of the&nbsp;<strong>BankAccount&nbsp;<\/strong>class, there is a separate and independent set of instance variables:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>m_holder<\/strong><\/li><li><strong>m_balance<\/strong><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">But what if we wanted to have a set of variables that are related to&nbsp;<em>all instances<\/em>&nbsp;of that class? For example, a bank might wish to keep track of:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Total number of accounts<\/li><li>Total deposits for all accounts<\/li><li>Total withdrawals for all accounts<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">for all <strong>BankAccount<\/strong>s.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can do this by defining:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>A set of&nbsp;<em><u>class variables<\/u><\/em>&nbsp;(also known as&nbsp;<em><u>static variables<\/u>,<\/em>&nbsp;or&nbsp;<em><u>static data members<\/u>)<\/em>,<\/li><li>A set of associated&nbsp;<em><u>class methods<\/u><\/em>&nbsp;(also known as&nbsp;<em><u>static methods<\/u><\/em>).<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,84,85,86,87]; title: ; quick-code: false; notranslate\" title=\"\">\nclass BankAccount\n{\n   \/\/ Constructors\n   BankAccount()\t    { this(&quot;&quot;, 0.0); }\n   BankAccount(String name) { this(name, 0.0); }\n   BankAccount(String name, double balance)\n   { \n        m_holder = name; m_balance = balance; \n        m_count++;\n   }\n\n   \/\/ Instance methods\n   \/\/ (NOTE: I&#039;m only using a finalize() method\n   \/\/        so that I can keep the instance counts\n   \/\/        straight for this very simple example.\n   \/\/        It&#039;s still not recommended unless you \n   \/\/        really know what you&#039;re doing.)\n   protected void finalize() throws Throwable\n   {\n        super.finalize();\n        m_count--;\n   }\n\n   public String getHolder()\t\n   { return m_holder; }\n\n   public double getBalance()\t\n   { return m_balance; }\n\n   public double deposit(double amount)\n   {\n        m_balance += amount;\n        m_totalDeposits += amount;\n        return m_balance;\n   }\n\n   public double withdraw(double amount)\n   {\n        m_balance -= amount;\n        m_totalWithdrawals += amount;\n        return m_balance;\n   }\n\n   \/\/ Class methods\n   public static int count()\t\n   { return m_count; }\n   \n   public static double totalDeposits()\t\n   { return m_totalDeposits; }\n   \n   public static double totalWithdrawals()\t\n   { return m_totalWithdrawals; }\n   \n   public static void main(String&#x5B;] argv)\n   {\n        BankAccount bh \n                = new BankAccount(&quot;Bryan Higgs&quot;, \n                                  1000000.00);\n        System.out.println(&quot;Account of: &quot; + bh.getHolder());\n        System.out.println(&quot;Balance   : &quot; + bh.getBalance());\n\n        BankAccount ep \n                = new BankAccount(&quot;Elvis Presley&quot;, \n                                  100000000.00);\n        System.out.println(&quot;Account of: &quot; + ep.getHolder());\n        System.out.println(&quot;Balance   : &quot; + ep.getBalance());\n\n        double amount = 15000.00; \/\/ I&#039;m not greedy!\n        ep.withdraw(amount);\n        bh.deposit(amount);\n\n        System.out.println(&quot;Number of accounts : &quot; + \n                        BankAccount.count());\n        System.out.println(&quot;Total Deposits    : &quot; + \n                        BankAccount.totalDeposits());\n        System.out.println(&quot;Total Withdrawals : &quot; + \n                        BankAccount.totalWithdrawals());\n   }\n\n   \/\/ Instance variables\n   String m_holder;\n   double m_balance;\n\n   \/\/ Class variables\n   static int m_count = 0;\n   static double m_totalDeposits = 0.0;\n   static double m_totalWithdrawals = 0.0;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Note:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The keyword&nbsp;<strong>static&nbsp;<\/strong>is used to specify that a member is a class member, rather than an instance member.<\/li><li>There is exactly one set of class variables for a given class.<\/li><li>Class variables exist whether instances of that class exist or not.<\/li><li>Class variables should be initialized in the class itself, not normally in a class constructor (Why?)<\/li><li>Class variables may be accessed without qualification within their class, or by explicit class name qualification outside their class.<\/li><li>Class methods do not have an implicit&nbsp;<strong>this&nbsp;<\/strong>variable (Why?)<\/li><li>Class methods may access class variables, but&nbsp;<em><strong>not<\/strong><\/em>&nbsp;instance variables (Why?)<\/li><li>Instance methods may call class methods, but&nbsp;<em><strong>not<\/strong><\/em>&nbsp;(usually) the other way around (Why?)<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Usage\"><\/span>Usage<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Class variables and class methods are used extensively in Java<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some examples of&nbsp;<em>class variables<\/em>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>PI<\/strong>&nbsp;&#8212; in the Java&nbsp;<strong>Math&nbsp;<\/strong>package<\/li><li><strong>out<\/strong>&nbsp;&#8212; in the Java&nbsp;<strong>System&nbsp;<\/strong>package<\/li><\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Remember&nbsp;System.out.print()&nbsp;???<\/p><\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some examples of&nbsp;<em>class methods<\/em>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>sqrt<\/strong>&nbsp;&#8212; in the Java&nbsp;<strong>Math&nbsp;<\/strong>package<\/li><li><strong>exit<\/strong>&nbsp;&#8212; in the Java&nbsp;<strong>System&nbsp;<\/strong>package<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Initialization\"><\/span>Initialization<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Class variables<\/em>&nbsp;may be initialized in the class definition (just like&nbsp;<em>instance variables<\/em>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Class variables<\/em>&nbsp;declared as&nbsp;<strong>final&nbsp;<\/strong><em><strong>must<\/strong><\/em>&nbsp;be initialized in the class definition (just like&nbsp;<em>instance variables<\/em>).&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Note that:<\/em><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><em>Class variables<\/em>&nbsp;are initialized&nbsp;<em>when the class is first&nbsp;<strong>loaded<\/strong><\/em>&nbsp;&nbsp;<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">while:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><em>Instance variables<\/em>&nbsp;are initialized&nbsp;<em>when the class instance is&nbsp;<strong>created<\/strong><\/em>.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Static_Initializers\"><\/span>Static Initializers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes we need to initialize things in a way that cannot be handled using such simple initializers.<em>Instance variables<\/em>&nbsp;have constructor methods to accomplish this.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Class variables<\/em>&nbsp;need a different mechanism:&nbsp;<em><strong>static initializers<\/strong><\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [15,16,17,18,19,20]; title: ; quick-code: false; notranslate\" title=\"\">\nclass Primes\n{\n    ...\n\n    private static int nextPrime(int startFrom)\n    { \n        \/* ... *\/ \n    }\n\n    ...\n\n    \/\/\/\/ Data \/\/\/\/\n    private static int knownPrimes = new int&#x5B;4];\n\n    static\n    {\n        knownPrimes&#x5B;0] = 2;\n        for (int i = 1; i &lt; knownPrimes.length; i++)\n            knownPrimes&#x5B;i] = nextPrime(knownPrimes&#x5B;i-1]);\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">A static initializer is like a class method, except:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>It has&nbsp;<em>no name<\/em><\/li><li>It accepts&nbsp;<em>no arguments<\/em><\/li><li>It returns&nbsp;<em>no value<\/em><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">There can be any number of static initializers &#8212; they are executed in lexical order when the class is loaded.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Static initializers are used, among other places, in classes that implement&nbsp;<em><strong>native methods<\/strong><\/em>&nbsp;(much later&#8230;).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Initialization_Blocks\"><\/span>Initialization Blocks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">You can also have an initialization block that does not have a static keyword prefix.&nbsp; It allows you to initialize instance fields, or to execute arbitrary code at instance initialization:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [9,10,11,12,13]; title: ; quick-code: false; notranslate\" title=\"\">\npublic class InitializerTest\n{\n  public static void main(String&#x5B;] args)\n  {\n    InitializerTest test1 = new InitializerTest();\n    InitializerTest test2 = new InitializerTest();\n  }\n\n  \/\/ Initialization block\n  {\n    System.out.println(&quot;Executing initialization block&quot;);\n    System.out.println(&quot;Count now &quot; + ++m_count);\n  }\n  static int m_count = 0;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">which produces:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Executing initialization block\nCount now 1\nExecuting initialization block\nCount now 2<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">There are a number of potentially useful applications of this technique.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>So far, we&#8217;ve looked at instance variables and methods &#8212; that is, variables and methods associated with a specific instance of a class. However, it is possible to associate both variables and methods with the class itself.&nbsp; These are known as class variables and class methods. Class vs. Instance Variables Consider the class&nbsp;BankAccount: For each&nbsp;instance&nbsp;of [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":57,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","_uag_custom_page_level_css":"","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-409","page","type-page","status-publish","hentry","entry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"ocean-thumb-m":false,"ocean-thumb-ml":false,"ocean-thumb-l":false},"uagb_author_info":{"display_name":"Bryan Higgs","author_link":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/author\/bryan\/"},"uagb_comment_info":0,"uagb_excerpt":"So far, we&#8217;ve looked at instance variables and methods &#8212; that is, variables and methods associated with a specific instance of a class. However, it is possible to associate both variables and methods with the class itself.&nbsp; These are known as class variables and class methods. Class vs. Instance Variables Consider the class&nbsp;BankAccount: For each&nbsp;instance&nbsp;of&hellip;","_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/409","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/comments?post=409"}],"version-history":[{"count":5,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/409\/revisions"}],"predecessor-version":[{"id":414,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/409\/revisions\/414"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/pages\/57"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/PracticalJavaProgramming\/wp-json\/wp\/v2\/media?parent=409"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}