Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Introduction to Classes and Objects

java class object

  • Please log in to reply
No replies to this topic

#1 mdebnath


    CC Newcomer

  • Member
  • PipPip
  • 17 posts
  • Programming Language:C, Java, C++
  • Learning:C, Java, C++

Posted 17 February 2013 - 02:51 AM

Classes and objects are the basic terminology and concepts of object oriented programming and Java is fully object oriented language. Everything you find in and around Java are object and classes. Even the primitive types such as as, int, float, char, double, boolean, we use in programming have their corresponding classes (they are called wrapper classes – Integer for int, Float for float, Character for char, Double for double, Boolean for boolean). There are thousands of classes in built in Java API library. It is practically impossible to know each and every class
and also does not require every time. But when you get the concept, it is pretty simple and easy to use them in your programming when requirement arises.


Classes,Objects, methods and instances variables

Classes are like blue print of an real-life-object, objects are its implementation or instances. Methods and instance variables or attributes are the content of a class. Lets draw an analogy, Vehicle is a class and truck, bus, SUV are some of its instances That means classes are an abstraction while objects are its concrete entity. Like a blueprint, an engineering design of a vehicle, you cannot drive the engineering drawing in much the same way you cannot drive a class. Got the idea?

When you drive a vehicle, pressing its accelerator pedal makes the it go faster i.e. You are sending a message to the object in this case, say a car, to move faster. This message is knows as method call and tells a method of the object to perform a task. Each vehicle provide many such capabilities and also has many attributes such as number of doors, colors, odometer reading, gas in tank etc. So in a class these attributes are specified by the class's instance variables.


Class declaration and object instantiation


The Employee class declaration contains two member function getName() and setName() that displays the attribute value in the screen and initializes the attribute name respectively. As we know class is like a blue print, we need to make an object of this class and call its method to initialize the attribute and display its value. The keyword public is an access modifier (we shall discuss more of access modifier later). Every class declaration contains keyword class followed immediately by the class name. Every class body is enclosed in a pair of braces.

package org.demo;

public class Employee {
    private String name;//attribute
    //member function or methods
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
}// end of class

Note: this is a keyword which refers to the object itself. Had we written the setName method as follows

public void setName(String n) {
        name = n;

the keyword this would not have been necessary. The statement name=n would do fine. As the variable name of the class attribute and the variable name of the setName parameter is same, we must use this keyword, otherwise Java compiler would be confused about which variable is to initialize.


Next, we'd like to use class Employee in an application. As we know method main begins the execution of every application. A class that contains method main is a Java application. Such class is special because the JVM can use main to begin execution. Class Employee is not an application because it does not contain main. Therefore if you try to execute Employee, you will get the error message:


Exception in thread "main" java.lang.NoSuchMethodError: main

To fix this problem we must either declare a separate class that contains a main method or place a main method in the class Employee.

Lets create a separate class containing method main to test Employee class.

package org.demo;
public class app {
    public static void main(String[] args) {
        Employee peter = new Employee();
        peter.setName("Peter Parker");
        System.out.println("Name :"+ peter.getName());

In this application, we would like to call Employee's setName() method to initialize the name of the employee and later use getName() method to display the name of the employee on the screen. Typically you cannot call a method that belong to another class until an object of that class is created. So we begin by declaring variable peter of type Employee. So in a sense each new class you create becomes a new type in Java that can be used to declare variable and create objects. Programmers can declare new class types as needed. Keyword new creates a new object of the class specified. The parenthesis

Employee peter = new

in combination with the class name represents a call to a constructor, which is similar to a method, but is used only at the time of creation of an object to initialize the object's data. If an explicit constructor is not written in a class, there is always a default (implicit) constructor provided by the class. So in this case the default constructor Employee() is used to create the object and the name attribute is initialized by default to null (String is an object, objects when instantiated in Java are always initialized to null by default).

Initializing objects with constructors


Lets write a variation of above program with the attribute name initialized with an explicit constructor.

package org.demo;
public class Employee {
    private String name; //attribute
    public Employee(String name){
        this.name = name;
    //member function or methods
    public String getName() {
        return name;
}//end of class

//-------separate java file-------------------------------------------------

package org.demo;
public class app {
    public static void main(String[] args) {
        Employee peter = new Employee("Peter Parker");
        System.out.println("Name :"+ peter.getName());    

So, you see, we can provide our own constructor to specify custom initialization for objects of our class. A programmer might want to specify a name for an Employee object when the object is created, as in

Employee peter = new
Employee("Peter Parker");

A constructor is almost same as method like, it has a name, take one/many or no arguments but with some important signification such as:

  • A constructor name must have the same name as its class
  • A constructor does not have any return type, i.e it does not return values (not even void) 
  • Normally, constructors are declared public  
  • If a class does not include a constructor, the class's instance variables are initialized to their default values
  • If a programmer declares any constructors for a class, Java will not create a default constructor for that class.

Note: default constructor is a constructor which is provided implicitly by java when you do not provide one.


Access modifiers


Most instance variable declaration are preceded with the private keyword. Like public, private is an access modifier. Variables and methods declared private are accessible only to methods of the class in which they are declared. The name in Employee can be used only in methods setName() and getName(). Declaring instance variables private is called data hiding. Data hiding is an important phenomenon of object oriented programming. When a program creates (instantiates) an object of class Employee, variable name is encapsulated (hidden) in the object and can be accessed only by methods of the object's class. Public keyword on the other hand indicate that the method is available to all, that is is can be called from outside that class declaration's body by methods of other classes. There is also another access modifier called protected, we shall discuss that later, in some other context.


Note: There is in fact another modifier like, providing no modifier (public, protected, private) at all. We shall discuss this in some other tutorial, as of now we shall discuss  only private and public.


About import declaration


The import declaration indicate to the compiler that the program uses a particular class. Classes such as System and String are in package java.lang, which implicitly imported into every Java program. Thus all programs can use package java.lang's classes without explicitly importing them. Classes which are considered to be in the same package are implicitly imported into the source code of files of other classes in the same package. Thus an import declaration is not required. Observe that, in the above example, the Employee class is used in the app class without any import statement because they belong to the same package org.demo.


 1. A house is to a blueprint as a/an_________ is to a class.
(1) class
(2) object
(3) constructor
(4) java

 2. Keyword for class declaration is
(1) class
(2) object
(3) void
(4) public

 3. Which keyword is used to create an object
(1) class
(2) private
(3) this
(4) new

 4. Keyword public is an
(1) function
(2) object
(3) class
(4) access modifier

 5. Which package java imports by default
(1) java.util
(2) java.io
(3) java.net
(4) java.lang

 6. What is the return type of a constructor
(1) int
(2) void
(3) nothing, not even void
(4) public

 7. The class String is in package
(1) java.io
(2) java.lang
(3) java.util
(4) none of the above

 8. Encapsulation means
(1) private
(2) data hiding
(3) public
(4) protected

 9. variable declared with private access modifier can only be accesses through
(1) member functions
(2) from main
(3) from any where within the package
(4) by dot(.) operator

 10. When a explicit constructor is written
(1) Java does not provide default constructors
(2) Java provides default constructors
(3) Java always provide default constructors
(4) None of the above

 11. Instance variables are nothing but
(1) objects
(2) member functions
(3) attributes
(4) parameters




Previous: Arrays | Next: Case Study | Back to Table of content

Edited by mdebnath, 09 March 2013 - 06:33 AM.

  • 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download