SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Classes
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write a class called Line that represents a line segment between two Points. Your Line objects should have the
following methods:
public Line(Point p1, Point p2)
Constructs a new Line that contains the given two Points.
public Point getP1()
Returns this Line’s first endpoint.
public Point getP2()
Returns this Line’s second endpoint.
public String toString()
Returns a String representation of this Line, such as "[(22, 3), (4, 7)]".

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// package classes;

public class Line {
	
	Point point1;
	Point point2;
	
	public Line(Point Point1, Point point2) {
		this.point1 = Point1;
		this.point2 = point2;
	}
	
	 public Point getPoint1() {
	        return point1;
	    }
	    
	    public Point getPoint2() {
	        return point2;
	    }
	
	public String toString() {
        // before calling toString on Point class override Point's toString method.
		return "[" +point1.toString()+", " +point2.toString()+"]";
        
	}
	
	

	public static void main(String[] args) {
		
		Point point1 = new Point(3,7);
		Point point2 = new Point(2,6);
		
		Line line = new Line(point1,point2);
		
		System.out.print("the string representation of the line is :"+line);
		
		
	}

}
Output:

the string representation of the line is :[(3,7), (2,6)]

 

0 0

Discussions

Post the discussion to improve the above solution.