ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 27

Updated on October 28, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Lesson 27: Working with classes in Java

The best way of solving a complex problem is by using the rule of “Divide and conquer”. The complex problem is divided into smaller manageable portions and each portion solved separately. The individual solutions make up the whole solution to the complex problem.

When Object Oriented programming languages were developed, what the developers of these languages had in mind is solving the problems using “Divide and conquer” approach. The problem can be divided into smaller manageable portion called “Objects” in Object Oriented programming and each solved by writing a Class code for each defined object.

Source

When we create a class in Object Oriented programming, we are writing code to do a particular job. That job might be to do with company employees, but not the company sales at the same time. We would write a separate class for the company sales.

By creating different classes for specific jobs, the classes can be re-usable. For instance, we can re-use the employee class in the same project or in other projects.

That is one beauty aspect of Object Oriented programming in solving business problems, classes can be re-used throughout the project without necessarily creating new ones for every problem to be solved.

In this lesson, we shall learn how to create and use classes in Java programming language and how to call such classes into action. When we create a class, we are writing code to solve a problem. To use such a class and solve the intended problem, we have to create the object of that class. We did this in the previous lessons but we’ll do it again here in more details.

For this lesson, you’ll need to create a new project. On the Java NetBeans IDE click File >> New Project, call the project “Examination”, you can delete all the comments for now. See the images below;

In the project, we are going to add another class that will handle the examination data. So, right-click Examination package, select “New” and create another Java class, call it “ExamDetails”.

Java global or field variables

In the previous lessons, we have been dealing with variables that cannot be accessed outside their parent methods. Such variables are called local variables and are said to have a local scope.

For us to be able to access variables from any method, we need those variables to have a global scope. Such variables are called global, instance or field variables.

Let us create four global variables that will hold the examination data. These four variables will be available to all the methods that we’ll write in this class, and won't be local to any one method. Set the four global variables in the class ExamDetails as shown below;

Visibility of global variables in Java

Just to test whether our four global variables are really global, we are going to test them in the main class. Go to the main class, Examination, and type the following line of code;

ExamDetails student = new ExamDetails();

In the above code, we are creating an object of the ExamDetails class in another method i.e. the main method. Now, attempt to access members (in this case, variables) of ExamDetails class in the main method and see if Java will recognize and list them.

Notice that as soon as you type the dot after the object name (student) Java NetBeans display a popup list of methods and properties available for the object. Our four global variables are listed as properties since they are not methods. The fact that they are on the list means that they have global scope. If they had local scope they wouldn't be on the list.

Now we can even set values to the properties and display them on the console. Try the following code;

It is not a good programming practice to make global variables to have a wide global scope like we have done. By doing so, we can lose track of what values are being held in them, and it therefore makes debugging our code a lot harder and messy. It's considered good coding to narrow the scope of global variables.

To make a global variable available only to a particular class, we add the Java keyword private just before the variable declaration. See the image below;

Including the keyword “private” will make the global variable only accessible inside ExamDetails class and not any other class. If you check on the main class now you’ll get a warning like shown below;

The warning states that the variable Student_name is private to ExamDetails class and cannot be accessed from the Examination class. Let us delete the extra code and try our earlier test to see if Java still recognizes our global variable.

As you can see, Java failed to recognize our four variables because they no longer have a global scope and therefore can't be seen from the Examination class. In the next lesson, we shall continue with Java classes and learn the use of Java class constructors and setter methods.

<< Lesson 26 | Lesson 28 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi ComfortB,

      I agree, Java has relation to C++ and actually some syntax are similar to Java. Thanks for the visit and comment. Have a nice one.

    • ComfortB profile image

      Comfort Babatola 

      7 years ago from Bonaire, GA, USA

      Java Has some similarities to C++, which I did in college, not that I remember much of it.

      It seems like Java is the new thing. If I do decide to learn Java, I know where to come. Great hub series. Voted up and useful.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi tammyswallow,

      How nice of you paying my hubs a visit. I do appreciate the wonderful comment up there and i really hope one day i will be able to write a book on Java programming. Thanks for the visit and comment.

    • tammyswallow profile image

      Tammy 

      7 years ago from North Carolina

      You are really a java expert. You could easily write a book on this subject!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi teaches12345,

      It is good to see you here, thanks for the visit and comment.

    • teaches12345 profile image

      Dianna Mendez 

      7 years ago

      Bravo! Another well written hub on this subject.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)