نمونه کلاسی که از به غیر از ویژگی های وراثت در جاوا از تمامی قابلیت های شی گرایی استاندارد جاوا استفاده کند.
– دو فیلد، متغیر عددی و متغیر رشته ای
– سازنده ی کامل و پیشفرض و کپی
– متدهای set و get برای هر دو فیلد برای حفظ قوانین کپسول سازی و چک کردن مقادیر مجاز برای ذخیره کردن در دو فیلد
– متد clone برای برگرداندن یک کپی از شی جاری
– متد equals برای مقایسه کردن شی جاری با یک شی همنوع دیگر
– متد toString برای چاپ کردن مقادیر تمام فیلدها
در نهایت هم یک کلاس Demo برای آزمایش تمام قابلیت های کلاس وجود دارد.
//FullClass
//Java Programming
//By: Marjan
//Website: Samiantec.ir
//Proudly Powered By Samiantec - Sina Moradi
class FullClass {
//Define variable[s] of class
private int x;
private String s;
public FullClass(int x, String s) { //Full Constructor
//Intialize variable[s] of new class with arguments
//We must indirect set variables because of variable domains.
//So we use set methods.
setX(x);
setS(s);
}
public FullClass() { //Default Constructor
//Intialize variable[s] of new class
x = 121;
s = "www.Samiantec.ir";
}
public FullClass(FullClass other) {//Copy Constructor
if (other == null) {
System.out.println("The object was null.");
System.exit(0);
}
x = other.x; //Copy x of other object in x of this object
s = other.s; //Copy s of other object in s of this object
}
public int getX() { //Indirect get x
return x;
}
public void setX(int x) { //Indirect set x
if (x == 0) { //Sample condition for x [Domain of x]
System.out.println("New x value is invalid.\nx can't be negative.");
System.exit(0);
}
this.x = x;
}
public String getS() { //Indirect get s
return s;
}
public void setS(String s) { //Indirect set s
if (s == "") { //Sample condition for s [Domain of s]
System.out.println("New s value is invalid.\ns can't be null string");
System.exit(0);
}
this.s = s;
}
public Object clone() { //clone Method
FullClass temp = new FullClass(this);
return temp;
}
public boolean equals(FullClass other) { //Compare Method (equals Method)
if (other == null)
return false;
if (x == other.x && s == other.s)
return true;
return false;
}
public String toString() { //toString Method
String temp = "x=" + x + " ; s=" + s;
return temp;
}
}
//FullClass Demo
//Java Programming
//By: Marjan
//Website: Samiantec.ir
//Proudly Powered By Samiantec - Sina Moradi
public class Demo { //Demo Class
public static void main(String[] args) {
FullClass cDefault=new FullClass();
System.out.println("Default: " + cDefault);
FullClass cFull=new FullClass(2015,"Sam");
System.out.println("Full : " + cFull);
System.out.println("Compare Default and Full: "+cDefault.equals(cFull));
FullClass cCopy=new FullClass(cFull);
System.out.println("Copy : " + cCopy);
FullClass cCloned=(FullClass)cFull.clone();
System.out.println("Clone: " + cCloned);
System.out.println("Compare Copied and Cloned: "+cCopy.equals(cCloned));
cCloned.setS("NewS");
System.out.println("toString: " + cCloned);
}
}
عالی بود کاش واسه وراثت و ترکیب هم اینطورسورس کد جامعی بزاری
ممنون
خواهش میکنم ، حتما