Bu makalemizde sizlere nesnesel
programlamanın temeli olan nesnesel kavramları anlatacağım.Bunun için sizlere kendi yazdığım
örnek kodları verip konuyu bu kodlar üzerinden anlatmaya çalışayım.[...]
Kısaca size örnek vereceğim koddan bahsedeyim.Aşagıdaki kodu tamamen ele alacak olursak
vermiş olduğum kod girilen kişi bilgilerini bir nesne de tutup nesnelerin eşit olup olmadığını
kontrol ediyor.Bu java.lang kütüphanesinin hazır fonksiyonu "nesnea.equals(nesneb)" diyerek te
yapılabilir.Ama amacımız nesnesel yaklaşımı öğrenmek.Şimdi kişinin ne gibi özellikleri olur onu tartışalım.
Ele alınan bir kişi isme ve soyisme sahip olmalıdır.Bunun yanına yaş kimlik no yazılabilir.Şimdi ne gibi
sınıflara bölebiliriz.Tek bir kişi (Person) classında bu verilen özellikler yer alabilir.Ama daha iyi bir yaklaşım,
isim (Name) ve kişi (Person) classları olacaktır.Yapmamız gereken şey isim sınıfını yaratıp bu sınıftan oluşturacağımız nesneyi kişi sınıfında kullanmak olacaktır.Sırası ile kodları vermeye başlayalım;
CODE:
package name;
public class Name {
private String first_name;
private String last_name;
// ============================================
/** Default constructor(No parameter) for Name class */
public Name() {
}
// ============================================
/**
* Constructor for the parameter first_name,last_name
* /
public Name(String first, String last) {
this.first_name = first;
this.last_name = last;
}
// ============================================
/** Getter method for first_name */
public String getFirst_name() {
return first_name;
}
// ============================================
/** Setter method for first_name */
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
// =============================================
/** Getter method for last_name */
public String getLast_name() {
return last_name;
}
// ==============================================
/** Setter method for last_name */
public void setLast_name(String last_name) {
this.last_name = last_name;
}
// ================================================
public boolean equals(Name arg0) {
return arg0.getFirst_name().equals(this.getFirst_name())
&& arg0.getLast_name().equals(this.getLast_name());
}
}
// ===================================================================================
Sınıf oluşturulduktan sonra yapmamız gereken şey sınıfa ait özellikleri aktarmak olacaktır.Biz biliyoruz ki isim
dediğimiz şey bir ad ve soy addan oluşur.Bu özellikler isteğe göre private ya da public tanımlanabilir.Ama benim önerim encapsulation açısından tanımladığınız özelliklerin private olması olacaktır.Çünkü bu sayede belirtmiş olduğunuz özelliklere kullanıcı direk ulaşamaz,onun yerine tanımlanmış olan bu özelliğin getter-setter larını kullanıp bu özelliğe atıf yapar.Tanımlama bittikten sonra nesne yaratma işlemine geçilir.Bu işleme constructor denilmektedir.Bu methodu kullanarak nesnenizi yaratmış olursunuz.Yukarıda ki kodda tanımlanmış olan 2 tane constructor bulunmaktadır.Bunlardan bir tanese parametresiz, diğeri ise parametreli olandır.Bu işlemler bittikten sonra tanımladığınız özelliklerin getter-setter ları yazılmalıdır.En altta bulunan public boolean equals(Name arg0) ise parametre olarak verilen arg0 nesnesi ile o an elimizde olan nesneyi karşılaştırmaktadır.Bu this ile yapılmaktadır.this o andaki nesneye atıf yapmaktadır.
========================================================================================
Şimdi kişi (Person) sınıfını tanımlayıp inceleyelim.
CODE:
package person;
import name.Name;
// ==================================================================
public class Person {
private Name name;
private int age;
private String id;
// ============================================
/** Default constructor */
public Person() {
}
// ============================================
/** Construct a Person with specified information */
public Person(String first_name, String last_name, int age, String Id) {
name = new Name(first_name, last_name);
this.age = age;
this.id = Id;
}
// ============================================
/** Getter method for age */
/** Return the age of person */
public int getAge() {
return age;
}
// ============================================
/** Setter method for age */
/** Set a new age */
public void setAge(int age) {
this.age = age;
}
// ===========================================
/** Method for age getOlder */
public int getOlder(int year) {
this.age = this.age + year;
return this.age;
}
// ===========================================
/** Getter method for Id */
/** Return the Id of person */
public String getId() {
return this.id;
}
// ===========================================
/** Setter method for Id */
/** Set a new Id */
public void setId(String id) {
this.id = id;
}
// ===========================================
/** Checker method for Id */
/** Id is valid if the Id's digit is 9 */
public boolean isValid() {
return this.id.length() == 9;
}
// ============================================
/** Getter method for Name */
/** Return the name of person */
public Name getName() {
return name;
}
// ============================================
/** Setter method for Name */
/** Set a new name */
public void setName(Name name) {
this.name = name;
}
// ============================================
/** Method for writing string form */
public String ToString() {
String output = " ";
output = output + "-->First name of Person:" + name.getFirst_name()
+ "n" + " -->Last name of Person: " + name.getLast_name()
+ "n" + " -->Age of Person:" + age + "n"
+ " -->The Id number of Person:" + this.id + "n";
return output;
}
// =============================================
/** Method for comparing two object */
public boolean equal(Person p1) {
//System.out.println(p1.ToString() + " " + this.ToString());
if (p1.name.equals(this.name) && p1.getId().equals(this.getId())
&& p1.getAge() == this.getAge())
return true;
else
return false;
}
// ============================================
}
javada en sevdiğim şeylerden biri tanımlamış olduğunuz bir sınıftan new operatörü ile oluşturduğunuz nesneyi başka bir sınıf içinde kullanabilmemizdir.Söylediğim şey tam olarak yukarıdaki kodda yapılmaktadır.Name sınıfından oluşturduğumuz nesneyi kişi sınıfında rahatlıkla kullanabiliriz.Aynı işlemler bu sınıf içinde yapılır.Bunlara ek olarak değişik methodlar (isValid,toString) eklenebilir.
Şimdi bu kodu test etmek için ayrı bir sınıf açıp(main şart) kodumuzu test edebiliriz.Bunun için testPerson diye bir sınıf oluşturalım ve ;
CODE:
//====================================================================================================================================================
package test_person;
import java.util.Scanner; //For the user to enter input!!!!
import person.Person; //For the Person Class
import name.Name; //For the name class
//==============================================================================================
public class TestPersonApp {
/**
* @param args
*/
//==============================================
public static void main(String[] args) {
// TODO Auto-generated method stub
/** ANother way of testing program!!!
Person person1 = new Person("Seyhan", "Ucar", 19, "140201024");
Person person2 = new Person("Oguz", "Kirat", 20, "150201024");
//Decide if two object are the same or not
if(person1.equal(person2)) //Compare two object using CompareTo method
System.out.println("People have the same information"); //Same object
else
System.out.println("People are different from each other."); //Different object
/**Create a Scanner for input */
Scanner input = new Scanner(System.in);
//==========================================
System.out.println("***************************************************************************");
System.out.println("*This program creates two person object and get the information from user.*");
System.out.println("*Decide if they are equal to each other by using class ' method *");
System.out.println("*************************************************************************n");
/**Get the choice from user*/
System.out.println("Please select the operation from above:");//Prompt the user selection operation
int choice = 0; //Selection variable
do
{
System.out.println("1-)Enter the person information:"); //1-)Get the person information
System.out.println("2-)Exit:"); //2-)Exit from the program
System.out.print("What is your choice ?:");
choice = input.nextInt(); //Get the choice
}while(choice < 1 || choice > 2); //Prompt the selection menu until 1 or 2 is entered
//===========================================================
switch(choice)
{
//============================================================
case 1: //İf the user enter the 1
//====================================================
int i = 0;
//=====================================================
/**These array holds the person information on index*/
/**For person Class */
Person[] person = new Person[2]; //Create an array whose types is Person
/**For the Name Class*/
Name[] name = new Name[2]; //Create an array whose types is Name
//=====================================================
do
{
//================================================
//Prompt the user to enter the first_name of person
System.out.print("Enter the person's first_name:");
/**While getting input the Scanner Class is used*/
String first_Name = input.next(); //Get the first name and assign to first_Name
//=================================================
//=================================================
//Prompt the user to enter the last_name of person
System.out.print("Enter the person's last_name:");
/**While getting input the Scanner Class is used*/
String last_Name = input.next(); //Get the last name and assign to last_Name
//=================================================
//=================================================
//Prompt the user to enter the age of person
System.out.print("Enter the person's age:");
/**While getting input the Scanner Class is used*/
int Age = input.nextInt(); //Get the age and assign to Age
//================================================
//================================================
//Prompt the user to enter the Id of person
System.out.print("Enter the Id number of person:");
/**While getting input the Scanner Class is used*/
String id = input.next(); //Get the Id and assign to Id
person[i] = new Person(); //Create a Object for each index of person array
name[i] = new Name(first_Name,last_Name); //Create a Object for each index of name array
person[i].setName(name[i]); //SetName method for Person Class and set name
person[i].setAge(Age); //SetAge method for Person Class and set Age
person[i].setId(id); //SetId method for Person Class and set Id
if(person[i].isValid())
System.out.println(" -->Id is vaLiD");
else
System.out.println(" -->Id is invaLiD");
//Check the Id validation
System.out.print(person[i].ToString()); //Print out the person information String type
i += 1; //Increment the index of each array
//=================================================
}while(2 > i); //Control the condition
//====================================================
/**Decide if two object are the same or not*/
if(person[0].equal(person[1])) //Compare two object using CompareTo method
System.out.println("People have the same information."); //Same object
else
System.out.println("People are different from each other."); //Different object
break;
//==================================================
case 2:
System.out.println("By bye.."); //Display by bye message
System.exit(0); //Exit
break;
}
//=====================================================
}
}
//====================================================================================================================================================
Şimdi kodumuz tamamlanmış durumda.Umarım nesne kavramlarına biraz daha aşina olmayı başarabilmişizdir.En yakın zamanda kaldığımız yerden devam edeceğiz.
seyhan
9 Kasim 2007 14:25