我從我工作的網站複製和粘貼此代碼。爪哇oop - 繼承
* A Line composes of two Points - a begin point and an end point.
*/
public class Line {
// The private instance variables
Point begin, end; // Object members - instances of the Point class
// Constructors
public Line(int x1, int y1, int x2, int y2) {
begin = new Point(x1, y1); // Construct the instances declared
end = new Point(x2, y2);
}
public Line(Point begin, Point end) {
this.begin = begin; // The caller constructed the instances
this.end = end;
}
// The public getter and setter for the private instance variables
public Point getBegin() {
return begin;
}
public Point getEnd() {
return end;
}
public void setBegin(Point begin) {
this.begin = begin;
}
public void setEnd(Point end) {
this.end = end;
}
public int getBeginX() {
return begin.getX(); // Point's getX()
}
public void setBeginX(int x) {
begin.setX(x); // Point's setX()
}
public int getBeginY() {
return begin.getY(); // Point's getY()
}
public void setBeginY(int y) {
begin.setY(y); // Point's setY()
}
public int[] getBeginXY() {
return begin.getXY(); // Point's getXY()
}
public void setBeginXY(int x, int y) {
begin.setXY(x, y); // Point's setXY()
}
public int getEndX() {
return end.getX(); // Point's getX()
}
public void setEndX(int x) {
end.setX(x); // Point's setX()
}
public int getEndY() {
return end.getY(); // Point's getY()
}
public void setEndY(int y) {
end.setY(y); // Point's setY()
}
public int[] getEndXY() {
return end.getXY(); // Point's getXY()
}
public void setEndXY(int x, int y) {
end.setXY(x, y); // Point's setXY()
}
// The toString() describe itself
public String toString() {
return "Line[begin=" + begin + ",end=" + end + "]";
// Invoke begin.toString() and end.toString()
}
public double getLength() {
return begin.distance(end); // Point's distance()
}
}
所以在這裏我們不得不類公共類點,並在第一個構造函數公共線的公共班線
.... 所以我們在這裏看到我們contruct類,它是一個構造函數和有沒有錯,它是如何使用或任何錯誤的是它的邏輯不存在
但也有這種方法公共點...這不是Point類,所以我們怎麼能在這裏使用這個方法。
我有點想出了這點,因爲Point的行爲類似於某種經濟類型,因爲在該方法中,我們不想開始並開始是一個點,一個對象定義了udner點類。所以我明白了,那是我們開始的唯一方法。但是一旦我們做了
public static void main(String[] args) {
Line l1 = new Line(new Point(7,8), new Point(2,5));
構造函數在這裏開始動作。所以最後形成了新的路線。但在構造方面沒有這樣的東西
return line;
或有返回線;但我們看不到它?我不知道。 然而,在這需要返回類型爲點的方法是有
return point;
但沒有
return x;
在構造
,我無法理解這裏的邏輯。
順便說一句,我們可以從這個方法
public Point getBegin() {
return begin;
}
以這種方式受益:
l1.getBegin().SOMEPOINTMETHOD;
但是如果我們沒有做這樣的事情,只是啓動
l1.getBegin();
我們會得到什麼樣的輸出?我知道輸出類型將指向,但由於點是一個對象,並且因爲我們沒有輸入對象的實例,所以我們不會得到任何正確的東西? Eclipse在這種情況下給出了一種奇怪的錯誤。
我知道它已經這麼久了,但我只是試圖理解這裏的邏輯,對不起,如果我太「虛假」,請不要立即判斷 - (同樣的情況下,主題)
但有返回類型的東西,所以'公共點xxx'實際上是一個普通的方法,而不是一個構造函數。就像一個方法'public int getSize(){...}'將會是一個帶有返回類型「int」的隨機方法。 – SomeJavaGuy
「,但在構造函數中不存在返回行;」 - 構造函數沒有返回類型。這樣想,因爲構造函數已經創建了該類的一個實例,所以不需要顯式返回。 – Mamun
如果我是你,我會先閱讀一些基本的Java閱讀材料,例如這個> https://docs.oracle.com/javase/tutorial/java/concepts/object.html和這個,這也是關於要點:)> https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8只要相信我,如果你認真學習Java,開始閱讀,那就是無論你得到多好的閱讀,都需要大量閱讀,所以你不妨開始新鮮:)! – Filip