What is the difference between a constructor and a method?

A constructor is a special type of method that is used to create an instance of an object. It is invoked when an instance of the object is created and it is used to set up the initial state of the object.

A method is a block of code that performs a specific task and is associated with an object. It is invoked by calling the method on the object.

Example:

Constructor:

public class Car {
private String make;
private String model;

public Car(String make, String model) {
this.make = make;
this.model = model;
}
}

Method:

public class Car {
private String make;
private String model;

public void setMake(String make) {
this.make = make;
}

public void setModel(String model) {
this.model = model;
}
}

What is the difference between a class method and an instance method?

A class method is a method that is defined in a class and can be called directly from the class without having to create an instance of the class first. An example of a class method is the __init__() method in Python.

An instance method is a method that is defined in a class and can only be called on an instance of the class. An example of an instance method is the __str__() method in Python.

What is the difference between an instance variable and a property?

An instance variable is a variable that is declared inside a class and is accessible from any method within that class. An example of an instance variable would be:

class Person {
private String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

A property is a special type of variable that is used to access a class’s member variables from outside the class. An example of a property would be:

class Person {
private String name;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

What is the difference between a class and an object?

Class: A class is a blueprint for creating objects. It is a template that describes the properties and behaviors of a type of object.

For example, a class called “Car” could describe the properties of a car, such as its color, make, model, and year. It could also describe the behaviors of a car, such as accelerating, braking, and turning.

Object: An object is an instance of a class. It is a concrete example of the class, with its own set of data and behaviors.

For example, a car object could be a specific car, such as a red Honda Accord from 2019. This object would have its own color, make, model, and year, and it would be able to accelerate, brake, and turn.