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
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?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started