Question regarding java inheritance As I know of, we need to declare an object f
ID: 3588876 • Letter: Q
Question
Question regarding java inheritance
As I know of, we need to declare an object first to use a method from its parent class.
However, I just noticed that just using method without any declaration of an object wouldn't cause an error
So here's a sample code below
//Parent class
package transport;
public class Vehicle
{
private int nWheels;
private double xPosition, yPosition;
public Vehicle(int nWheels)
{
this.nWheels = nWheels;
}
public void setPosition(double xPosition, double yPosition)
{
this.xPosition = xPosition;
this.yPosition = yPosition;
}
public double getXPosition()
{
return xPosition;
}
public double getYPosition()
{
return yPosition;
}
public void changePositionBy(double xDelta, double yDelta)
{
xPosition += xDelta;
yPosition += yDelta;
}
public static void main(String[] args)
{
MarsRover mr = new MarsRover();
}
}
---------------------------------
As my understading, we need to do like below
childClass child = new childClass();
childClass.setPosition(0, 0);
childClass.changePositionBy(x, y);
but I just noticed that below won't cause an error
setPisition(0, 0);
changePositionBy(x, y);
would both ways work as the same?
if so, is there any reason why we need to declare an object?
I mean, is it somehow better coding?
Explanation / Answer
Answer: If we are accessing the methods with in the same class and also not accessing from static methods them we dont need to create an object of the class.
But if we are calling these methods from static methods like main() then we have to create an object to access these methods because static methods can call static methods only. This is the difference.
Below two approaches are true when method calling not happening in static method and it is happing with in same class.
childClass child = new childClass();
childClass.setPosition(0, 0);
childClass.changePositionBy(x, y);
setPisition(0, 0);
changePositionBy(x, y);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.