Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Principles Programming And Performance

Authors: Patrick O'Neil

1st Edition

1558603921, 978-1558603929

More Books

Students also viewed these Databases questions

Question

In an Excel Pivot Table, how is a Fact/Measure Column repeated?

Answered: 1 week ago