Thursday, November 19, 2009

SCJP 1.6 Study Guide: Object Orientation Part 1

Object Orientation

To be a Sun Certified Java Programmer, object-oriented concepts in Java should be second nature to you. In this section we will talk about the OO features of Java like encapsulation, inheritance, and polymorphism. We will continue our discussion in implementing interfaces, return type declarations and static variables and methods. We will also discuss topics like overloading/overriding, casting and coupling and cohesion. This is the second section of this series if you want to read the first section go here.

Encapsulation and Inheritance

Encapsulation. Encapsulation results to code flexibility and maintainability by hiding implementation details(instance variables) behind public interfaces(methods).

To implement encapsulation you must do the following:
  • Hide instance variables by using the private access modifier.
  • Create public methods to access private instance variables. This will ensure that users of your classes will go through the method where you can implement checks that will assure you that your classes will be used the right way. These methods are called getters and setters(some call them accessors and mutators). For these methods it is recommended to use the JavaBeans naming convention(getXxx and setXxx).
Example:
(No Encapsulation)
public class Person{
public double weight;
}
public class TestPerson{
public static void main(String[] args){
Person person = new Person();
person.weight = -1.0; // you probably don't want this to happen
}
}
(With Encapsulation)
public class Person{
private double weight;

// getter
public double getWeight(){
return weight;
}

// setter
public void setWeight(double weight){
if(weight > 0){
this.weight = weight; // better, right?
}
}
}
public class TestPerson{
public static void main(String[] args){
Person person = new Person();
person.weight = -1.0; // this will compile but
// will not change the value
// of weight
}
}
Inheritance. Inheritance as defined by Answers.com refers to the process of genetic transmission of characteristics from parents to offspring. That definition somehow mirrors what inheritance is in Java.

Inheritance in Java allows one class called the subclass to extend another class, the super class. Where the subclass by extending the super class inherits some or all of the super class' members(instance variables and instance methods) depending on the member's visibility.

You implement inheritance by using the extends keyword with the class declaration.

Example:
public class Person{
private String firstName;

public void setFirstName(String firstName){
this.firstName = firstName;
}

public String getFirstName(){
return firstName;
}
}
public class Student extends Person{}
public class TestStudent{
public static void main(String[] args){
Student student = new Student();

System.out.println(student.getFirstName());
// wait Student has no getFirstName()
// well, Student got it thru inheritance from Person
student.setFirstName("Bob");
System.out.println(student.getFirstName());
}
}
Running TestStudent results to:
null
Bob
A class can only extend one class. You cannot say:
public class Student extends Person, Animal{}
The above example will not compile because there's no such thing as multiple inheritance in Java, but you must know that every class that Java programmers create implicitly extends the Object class.

Example:
public class TestClass{}
public class TestTestClass{
public static void main(String[] args){
TestClass test = new TestClass();
System.out.println(test.toString());
// where did toString() come from?
// toString() returns a String representation
// of an object in this case
// a reference to the object test

// let's check with instanceof operator
if(test instanceof TestClass){
System.out.println("test is a TestClass");
// of course we declared it to be
// a type of TestClass
}

if(test instanceof Object){
System.out.println("test is an Object");
}
}
}
Running TestTestClass results to:
TestClass@addbf1
test is a TestClass
test is an Object
Inheritance is usually used for the following purposes:
  • Code reuse. Which is shown by our Person and Student class. We created a generic Person class with a firstName, getFirstName() and setFirstName() and then created a specialized Student class in which we need a firstName again but since the Person class already has them we just need to extend it and we'll be able to set and get the firstName of any Student object too.
  • Polymorphism. Polymorphism in Java allows any subclass of a superclass be treated as type of the superclass.
Example:
public abstract class Animal{
public abstract void cry();
}
public class Dog extends Animal{
public void cry(){
System.out.println("Aw..Awoo..");
}
}
public class Cat extends Animal{
public void cry(){
System.out.println("Me..Meowwww..");
}
}
public class Vet{
public void vaccinate(Animal animal){ // polymorphism in action
animal.cry();
}
}
public class TestVet{
public static void main(String[] args){
Dog dog = new Dog();
Cat cat = new Cat();
Vet vet = new Vet();

// polymorphism in action
vet.vaccinate(dog); // This will compile and run since
vet.vaccinate(cat); // Dog and Cat are subclasses of Animal
}
}
Running TestVet results to:
Aw..Awoo..
Me..Meowwww..
The example above is patterned from an example in Head First Java, 2nd Edition.

First, we've defined an abstract Animal class with abstract method cry(). Next we've defined Dog and Cat classes which extends Animal and both provided an implementation for the cry() method. We've then created a Vet class and defined a vaccinate() method which accepts an object of type Animal. We declared the method parameter for vaccinate() to be of type Animal so that we don't need to create several other vaccinate() methods each time we come up with a different class that extends the Animal class. We don't care what class is passed to the vaccinate() method as long as it can be treated as an Animal.

Observe that when we ran TestVet, the JVM still executed the cry() method of for the Dog and the Cat class. We'll discuss why this happened in the next post.

Polymorphism is implemented in interfaces as well, which means that a class can be considered a type of an interface if that class implements the interface.

Example:
public interface Rollable{
void roll();
}
public class Dog extends Animal implements Rollable{
public void cry(){
System.out.println("Aw..Awoo..");
}

public void roll(){
System.out.println("The dog is rolling...");
}
}
public class TestRollableDog{
public static void main(String[] args){
Dog dog = new Dog();

if(dog instanceof Rollable){
System.out.println("dog is a Rollable");
}
}
}
Running TestRollable results to:
dog is a Rollable
IS-A.For the exam, we need to be able to determine if classes demonstrates IS-A or HAS-A relationship.

The IS-A relationship is based on class inheritance and interface implementation. You can always test this relationship by using the instanceof operator.

Example:
public class Animal{}
public interface Rollable{}
public class Dog extends Animal implements Rollable
public class Shitzu extends Dog
Listing the relationships we have:
  • Shitzu extends Dog, which means Shitzu IS-A Dog
  • Dog extends Animal, so Dog IS-A Animal (we don't really care about grammar here.:D)
  • Dog implements Rollable, so Dog IS-A Rollable
  • Since Dog IS-A Animal and Shitzu IS-A Dog we can say that Shitzu IS-A Animal. This only shows that a class has an IS-A relationship with anything further up the inheritance tree.
  • Q: Can we say Shitzu IS-A Rollable?
HAS-A. In contrast with IS-A relationship, HAS-A relationship is based on usage/existence/possession instead of inheritance.

Example:
public class Person{}
public class Student extends Person{
private Course course;
}
public class Course{}
In the above example we can say that Student IS-A Person and at the same time Student HAS-A Course. As you might have observed, if class A is an instance variable of class B then class B HAS-A class A.

That's it for this part we will discuss polymorphism deeper with the next post.

42 comments:

喜早 said...

我從來不認為不同意我的看法就是冒犯 ..................................................

過分 said...

pleasure to find such a good artical! please keep update!! ........................................

香蕉哥哥 said...

Better say nothing than nothing to the purpose. ........................................

寧年 said...

彰化聊天室豆豆聊聊天080人聊天室尋夢元聊天性愛性交女優電影王國小2館小小遊戲女性愛技巧女性做愛技巧女性高潮圖女同志天室女同志色圖片情網站女同志色網站女同志區女同志聊天?女同志影片線上看女同動畫女同聊天網女同聊天?女同圖片女身遊戲女性性愛技巧女性高潮用品小可愛圖片小老鼠咆嘯分享論壇小弟影片網小杜情網小肚小野貓貼圖gogogirl視訊美女 網路小說 哈比寬頻成人貼圖區

v辰原 said...

你的部落格很棒,我期待更新喔........................................

JesseniaT_Orndorff1021 said...

IT IS A VERY NICE SUGGESTION, THANK YOU LOTS! ........................................

BlancaMcleroy1230 said...

Nice blog85cc,咆哮小老鼠,85街,免費影片,情趣爽翻天,愛戀情人用品,交友找啦咧,線上a片,女同志聊天室,sexy,色情網站,網愛聊天室,情色性愛貼圖,小穴,性愛姿勢,陰脣室,成人圖貼,性愛技巧,a片論壇,色情,85c,sexy網,人妻,脫衣,6k,18禁,手淫,性幻想,77p2p,情色,1007,85c,0401,後宮,色情,淫蕩,正妹,77p2p,ut室

瑜吟 said...

喔!最悲慘的事並非夭折早逝,而是當我活到七十五歲,卻發現自己從未真正活過。 ..................................................

jon0301astabron said...

激情成人聊天室情色成人辣妹胸部辣妹視訊露奶辣妹自拍三點全露內衣秀台灣成人貼圖成人電影院三點全裸免費視訊辣妹av圖裸體自拍色情聊天美女視訊g點色情訊息淫女火辣av辣妹圖片免費視訊聊天室情色天空調情上床圖片裸體自拍走光照片走光視訊情色成人18成人區火辣美女成人vcd成人影片下載本土av性愛情慾淫妹美女聊天性愛聊天室女生自慰影片免費看a圖淫婦巨乳辣妹視訊成人女生自慰方法免費情色限制級a片穿幫情色下載情色網站

冠琴 said...

喜歡你的部落格,留言請您繼續加油...............................................................

智能 said...

A friend to everybody is a friend to nobody..............................................

M12aeganT_Moe12 said...

85成人片免費看 視訊交友vino 一夜情情色聊天 免費觀看影片 視訊交友中心 免費最新女優影片 性感走光照片 免費線上看成人影片 辣妹偷拍貼圖 男女聊天室 愛愛天堂 情趣內衣寫真 18禁成人影城 少女辣妹遊戲18 洪爺影城av 成人卡通a片 情色+貼圖 色情貼圖區 一夜情網站, 383成人 完美女人影音視訊 live 秀 玩美女人國 性感絲襪美女 辣妹交友 人妻自拍裸體 熟南熟女聊天室 a片下載 免費視訊聊天室 a圖裸體女生 天天看正妹美女寫真館 85cc成人長片 免費a片 嘟嘟 997770 台灣情色貼圖 一夜情買援交妹 情人視訊網 鋼管秀視訊 av網站 辣妹自拍 大奶辣妹照片 sex 85cc影片 日本巨乳寫真下載 情色性愛圖貼 後宮電影院 限制級 0204交友 日本性愛影片 洪爺走光自拍照片圖片

730A_ngelinaRabideau0 said...

凡是遇到困擾的問題,不要把它當作可怕的,討厭的,無奈的遭遇,而要把它當作歷練、訓練和幫助。 ..................................................

彥安彥安 said...

大肚能容,了卻人間多少事,滿腔歡喜,笑開天下古今愁。 ..................................................

張孟勳 said...

After a storm comes a calm...................................................

俊翔 said...

教育無他,愛與榜樣而已 ............................................................

禎峰 said...

當一個人內心能容納兩樣相互衝突的東西,這個人便開始變得有價值了。..................................................................

佳燕 said...

良言一句三冬暖,惡語傷人六月寒。....................................................................

韋以韋以 said...

生存乃是不斷地在內心與靈魂交戰;寫作是坐著審判自己。.................................................................

堅強堅強 said...

當一個人內心能容納兩樣相互衝突的東西,這個人便開始變得有價值了。............................................................

陳登陽 said...

人有兩眼一舌,是為了觀察倍於說話的緣故。............................................................

吳婷婷 said...

人生是故事的創造與遺忘。............................................................

溫緯李娟王季 said...

如果你批評他人。你就沒有時間付出愛............................................................

云依恩HFH謝鄭JTR安 said...

Some people cannot see the wood for the trees.............................................................

于倫 said...

No garden without its weeds.............................................................

KyungBivo中如 said...

雖天地之大,萬物之多,而惟吾蜩翼之知。..................................................

祥明祥明 said...

要持續更新下去喲!!期待~~..................................................................

s陳andersr睿afae婷l said...

Judge not a book by its cover.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

黃子軒 said...

我來湊熱鬧的~~^^ 要平安快樂哦............................................................

劉黃志宇建娥 said...

好喜歡你的部落格唷,剛下班,要去睡了!!!掰~~............................................................

吳林怡廷佳宇 said...

不要去想沒拿到的東西,多想想自己手裡所擁有的..................................................

建宗穎彰 said...

認識自己,是發現妳的真性格、掌握妳的命運、創照你前程的根源。.......................................................

吳承侯政霖虹 said...

傻氣的人喜歡給心 雖然每次都被笑了卻得到了別人的心..................................................................

偉曹琬 said...

Make yourself necessary to someone..................................................................

信陳定 said...

一個人的際遇在第一次總是最深刻的,有時候甚至會讓人的心變成永遠的絕緣。......................................................................

小草 said...

感謝分享 功德無量............................................................

怡屏 said...

happy to read~ thank you!............................................................

于庭吳 said...

很棒的分享~~~來留個言囉~~~~............................................................

惠NorrisBradwell041花 said...

好熱鬧喔 大家踴躍的留言 讓部落格更有活力..................................................

孫邦柔 said...

卡爾.桑得柏:「除非先有夢,否則一切皆不成。」共勉!.................................................................

Sandeep said...

Great article

Thanks for the information

http://extreme-java.blogspot.com/2008/07/overloading-rules-in-java.html

Sandeep said...

Great article

Thanks for the information

http://extreme-java.blogspot.com/2007/12/method-overriding-rules-in-java.html

Post a Comment