Is a special type of method which is called automatically when an object is created?

  • Everything in Java is part of a class
    • This includes all functions (known as methods -- i.e. member functions)
    • even main() is a method of a class
  • Classes are declared in a similar form as in C++.
    • This includes the ability to categorize members as public or private (visibility modifiers)
    • However, in Java, public and private are modifiers placed on each member.
    • Small class declaration example: Circle.java

Creating Objects

Objects are created from a class by using the new operator, and they must be attached to a reference variable. Two steps:
  1. Declare the object reference variable
  2. Create the object with the new operator and attach it to the reference variable

Format

  ClassName objectReference;
  objectReference = new ClassName();

(or combined into one statement)

  ClassName objectReference = new ClassName();
Examples:
  Circle myCircle;		// where Circle is a class
  myCircle = new Circle();

  Dog fido = new Dog();		// where Dog is a class
Caution: Since the name used to refer to an object is a reference variable, and not the object itself, it is important to note that any assignments done on such a variable are just on the reference. For example, if we create two objects, and then assign their variables together:
  Circle c1 = new Circle();
  Circle c2 = new Circle();

  c1 = c2;
... the last statement (c1 = c2) does not copy circle c2 into c1. Instead, it copies the reference varaible c2 to c1, which means that both reference variables are now referring to the same object (the second one, c2).

Using Objects

Once an object is created, access the object's internal methods and data with the dot-operator. Format:
  objectReference.data
  objectReference.method(arguments)   // a call to a method
Example:
  Circle c1 = new Circle();
  c1.radius = 10;		// access radius instance variable

  // compute and print the area with the findArea method
  System.out.print("Area = " + c1.findArea());

Constructors

  • Constructors work in much the same way they do in C++
    • Same name as the class, no return type
    • Can have multiple constructors (function overloading)
    • Primary purpose is to handle object initialization
  • A constructor is automatically invoked when an object is created with new.
      c1 = new Circle();    // invokes default constructor
      c2 = new Circle(9.0)  // invokes a constructor with one parameter
    

Objects as Method Parameters

  • Remember, objects are created with the new operator. The name we use is a reference variable
  • When an object is passed into a method, the reference variable is copied into the method's local parameter (just like with arrays) -- method parameter becomes a reference to the original object
  • Bottom line: When an object is passed into a method (by its reference variable), the method has access to the original object. Changes to the object (from inside the method) will affect the original

Class Variables and Methods -- static vs instance

The modifier static can be used on variables and on methods
  • Variables
    • A static variable is shared by all instances of a class. Only one variable created for the class.
    • Instance variable (not static) -- each object (i.e. each instance of a class) gets its own copy of such a variable
  • Methods
    • A regular method (instance method) can only be called by an object (an instance of the class)
    • A static method (class method) can be called without creating instances of a class. Called through class name or object name -- but a better practice to call through the class name (to help remind that they are static). Example: Math.round(x)
  • access
    • Static variables can be accessed from both instance methods or static methods.
    • Instance variables can not be accessed from static methods (since instance variables only exist when an object exists). Instance variables can be accessed from instance methods
To make a class variable constant, add the keyword final as a modifier on the declaration. It's better to make your constants also static -- since the value won't change, it's more efficient to have one variable shared by the entire class.

Example

 class Student
 {
   private int testGrade;		// instance variable (non-static)
   private static int numStudents = 0;	// static variable (class variable)
   private final static int pointsPossible = 100;       // class constant

   public Student()
   {   testGrade = 0;   }

   public void setGrade(int gr)
   {   testGrade = gr;  }

   public int getGrade()
   {   return testGrade;  }

   public static void incrementNumStudents()
   {   numStudents++;   }

   public static int getNumStudents()
   {   return numStudents;  }  

 }
In this sample code:
  • testGrade is an intance variable. Each object of type Student will have its own copy of testGrade
  • numStudents is a class varaible (static). There is only one variable shared by the whole class. The variable's value can be changed, but changes are seen by all objects
  • pointsPossible is a class constant. There is only one variable (because of static), and its value cannot be changed)
  • setGrade and getGrade are instance methods. They must be called through individual objects
  • incrementNumStudents and getNumeStudents are static methods. They cannot access instance varaibles of the class, but they can be called through the class name, regardless of whether any objects have been created
Student.java - You can get a copy of this code example here, along with a small sample main() program that illustrates some calls.

The Keyword this

  • In C++, this is a pointer to the current calling object (from inside a class function)
  • In Java, this is a reference varibable to the current calling object (from inside an instance method)
  • In Java, this can also be used to call one constructor from another in a class. Use it like the function name in the call. Example:
      public Date(int m, int d, int y)	// constructor with 3 params
      {
         month = m;     day = d;     year = y;
      }
    
      public Date(int m, int d)		// constructor with 2 params
      {
         this(m, d, 0);			// calls constructor with 3 params
      }
    

Fraction class example

In my COP 3330 course, I typically use a Fraction class as my first full C++ class illustration. Here's the corresponding class in Java.
  • class Fraction

More class examples in Deitel Chapter 8

Which special type of method is called when an object is created?

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Which method is automatically created when an object is created?

Every class should have a method with the special name __init__. This initializer method is automatically called whenever a new instance of Point is created. It gives the programmer the opportunity to set up the attributes required within the new instance by giving them their initial state/values.

Which method is called automatically when an object is created Python?

For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method. The __str__ method is called when you print() an object. On the other hand, user-defined methods, like stefi. run() , are called explicitly.

When an object of class is created which special function is called automatically?

I think there one is the correct answer because in C++ declaring a object means its creation. :). A constructor is always called when an object is initialized, not declared and certainly not "used". A constructor is called whenever an object is created and declaration is nothing but creation of an object.