Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Exercise 1.6: Code pasted below Code: class XYLine { XYPoint start; // An object variable. XYPoint end; // Another one. public void printSlope () {

Exercise 1.6: Code pasted below

image text in transcribed

Code:

class XYLine {

XYPoint start; // An object variable.

XYPoint end; // Another one.

public void printSlope () {

double s = (end.y - start.y) / (end.x - start.x);

System.out.println ("Slope = " + s);

}

}

class XYPoint {

double x;

double y;

public XYPoint(double x, double y) {

this.x = x; // differentiate between parameter x and instance variable

this.y = y;

}

public XYPoint() {

x = Math.random() * 10;

y = Math.random() * 10;

}

}

public class Main {

public static void main (String[] argv) {

// Make a new instance of an XYPoint object

XYPoint p = new XYPoint();

XYPoint p2 = new XYPoint(5, 5);

// Access its variables:

double d = Math.sqrt(p.x*p.x + p.y*p.y);

System.out.println(d);

d = Math.sqrt(p2.x*p2.x + p2.y*p2.y);

System.out.println(d);

}

}

Class Constructors Often we want to immediately fill in some instance variables when we create a new object. A class constructor allows us to easily do that class XYPoint i double x; double y; public XYPoint(double x, double y) i this . x-x; this.y - y; differentiate between parameter x and instance variable public XYPointO xMath. randomO * 10; y-Math.randomO 10; public class Main { public static void main (String[] argv) I Make a new instance of an XYPoint object XYPoint p new XYPointQ; XYPoint p2 new XYPoint(5, 5); Access its variables: double d Math.sqrt (p.x*p.x p.y*p.y); System.out.println(d); d-Math. sqrt(p2.xp2.x + p2.y*p2.y); System. out.println(d) Note: A class can have several different constructors with different parameters Here we are using the this keyword to distinguish between the x variable that arrives as a parameter to the constructor and the instance variable x which is part of "this" new object being created What are the benefits of using a constructor? What could go wrong if we didn't have one? Exercise 1.6: Create at least two different constructors for the XYPoint and XYLine classes. Add a function that calculates the length of a line. Create an array with 10 random lines and print the length of each one

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_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

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

Get Started

Students also viewed these Databases questions

Question

How the constructor prepares for the competition

Answered: 1 week ago

Question

=+ a. How does this change affect the incentives for working?

Answered: 1 week ago