All posts by JazzerCoder

‘this’ pointer in C++

The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ‘this’ pointer is a constant pointer that holds the memory address of the current object. ‘this’ pointer is not available in static member functions as static member functions can be called without any object (with class name).
For a class X, the type of this pointer is ‘X* const’. Also, if a member function of X is declared as const, then the type of this pointer is ‘const X *const’.

Following are the situations where ‘this’ pointer is used:

1) When local variable’s name is same as member’s name

#include
using namespace std;
 
/* local variable is same as a member's name */
class Test
{
private:
   int x;
public:
   void setX (int x)
   {
       // The 'this' pointer is used to retrieve the object's x
       // hidden by the local variable 'x'
       this->x = x;
   }
   void print() { cout << "x = " << x << endl; }
};
 
int main()
{
   Test obj;
   int x = 20;
   obj.setX(x);
   obj.print();
   return 0;
}

Output:

x = 20

Easy reading from Keyboard in Java

We can use Scanner class

Import first:

import java.util.Scanner;

Then we go this way for integers.

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

If we rather a string line:

String text= scan.nextLine();

Easy piece!

Note: If you are using nextInt() with nextLine() it may probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine().

Static

Static

Los métodos static no requieren una instancia de la clase, ni pueden acceder a los datos de la clase/objeto de forma implícita.

Un método static se distingue en algunos lenguajes de programación con la palabra clave static colocada en algún lugar en la firma del método.

Los metodos estaticos se cargan en memoria en tiempo de compilación y no a medida que se ejecutan las líneas de código del programa. Van precedidos del modificador static. Para invocar a un método estático no se necesita crear un objeto de la clase en la que se define:

  • Si se invoca desde la clase en la que se encuentra definido, basta con escribir su nombre.
  • Si se le invoca desde una clase distinta, debe anteponerse a su nombre, el de la clase en la que se encuentra seguido del operador punto (.) .metodoEstatico

Suelen emplearse para realizar operaciones comunes a todos los objetos de la clase.

Dado que los métodos estáticos tienen sentido a nivel de clase y no a nivel de objeto (instancia) los métodos estáticos no pueden acceder a datos miembros que no sean estáticos.

C++

Class MyClass {
public:
static float areaCirc (radio){
  //do some math here
  return area;
 }
};

Java

public class Mechanics {

    // add an instance variable for the object ID    
    private int cadence;
    private int gear;
    private int speed;

    //static method
    public static double speedURM (int dist, float time){
     // do some math here
    return urmSpeed;
}
}

Static methods

Static

 

Static methods neither require an instance of the class nor can they implicitly access the data (or this, self, Me, etc.) of such an instance. A static method is distinguished in some programming languages with the static keyword placed somewhere in the method’s signature.

In statically typed languages such as Java, static methods are called “static” because they are resolved statically (i.e. at compile time) based on the class they are called on and not dynamically as in the case with instance methods which are resolved polymorphically based on the runtime type of the object. Therefore, static methods cannot be overridden.

C++

Class MyClass {
public:
static float areaCirc (radio){
  //do some math here
  return area;
 }
};

Java

public class Mechanics {

    // add an instance variable for the object ID    
    private int cadence;
    private int gear;
    private int speed;

    //static method
    public static double speedURM (int dist, float time){
     // do some math here
    return urmSpeed;
}
}

Local and Anonymous Inner Classes in Java

Local and Anonymous Inner Classes in Java

Local Inner Classes in Java

If an inner class has been defined within a code block (typically within the body of a method), then such an inner class is called a local inner class. A local inner class is not a member of the enclosing class and hence it can not have any access specifier. A local inner class will have access to all the members of the enclosing class and it’ll have access to the local final variables in the scope it’s defined.

Example: a typical local inner class

public class EnclosingClass{
	...
		public methodName()
		{
			//...definition of the local inner class
			class LocalInnerClass 
			{
				...

			}
		...
}

Anonymous Inner Classes in Java

If an inner class has been declared without a name and within a code block (typically within the body of a method) then such an inner class is called an anonymous inner class. Since such an inner class doesn’t have a name associated, so it’ll be accessible only at the point where it is defined.

Example: a very common usage of an anonymous inner class

public class GUI extends JFrame{
	…
		public void buildComponents(){
		…
		button1 = newJButton();
		…
		button1.addActionListener(new java.awt.event.ActionListener(){
		public void actionPerformed(java.awt.event.ActionEvent ae){
		…
		…
		}
		});
		…
		…
	}
}

Since, an anonymous inner class doesn’t have a name, so it can’t have a named constructor. But, it can have an instance initializer. Access rules for anonymous inner classes are same as that of local inner classes. Similar to a local inner class, an anonymous inner class can also not have any access specifier attached to it.

Are anonymous inner classes same as local inner classes?

Yeah…, an anonymous inner class is a local inner class in all means except that it doesn’t have a name and hence it can’t be used at any other point except at the point where it has been defined. The other difference is that it can’t have a named constructor again for the same reason that it doesn’t have a name.