Solved

Java - confuse using abstract class and class

Posted on 2012-03-15
13
490 Views
Last Modified: 2012-03-17
First I like to thankyou for yan's help. Now I have to create a abstract class and class. I hope Yan is free and able to give me explanation how it works. many thanks in advance
=
*** SchoolContactInfo
abstract class SchoolContactInfo implements Comparable <SchoolContactInfo>{
    private String name;
    private String phone;

    // Constructor
    public SchoolContactInfo(String Name, String Phone) {
          name = Name;
          phone = Phone;
    }

    public String getName() {
          return name;
    }

    public void setName(String name) {
          this.name = name;
    }

    public String getPhone() {
          return phone;
    }

    public void setPhone(String phone) {
          this.phone = phone;
    }

   public  int compareTo(SchoolContactInfo s){

       return s.getName().compareTo(name);

    }
}

==========================================================
SchoolContact class
==========================================================
public class SchoolContact {

*** dont know how to link to SchoolContactInfo. Should I move the code from SchoolContactInfo to here....

      
}

===========================================================
Main() - school address
=============================================================
0
Comment
Question by:unistudent
  • 8
  • 5
13 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 37727811
Abstract class is normally a class which has at least one  asbtract method.
Abstract method is the method for which only signature is provided in the abstact class, but implementation is provided in the subclsses of this abstract class.
So you cannot create and instance of abstract class but you can create and instance of real subclass of the abstract class

an example of abstract class can be say class Shape which can have abstract methods double area()
and
double perimeter();

and then you can have subclass say Square or Circle where you would provide
real implementations of these methods in the real classes.


what exactly they meant in this SchollContactInfo I'm not sure I fully unsretsnd
But we can invenet soemthing like that:

I'm not sure thsi is the best way of using absrtcat class, but at least it is
possible and correct.

So we have an abstract method getMajor()
and we implement it differently in each of the two subclasses; see code below
  abstract class SchoolContactInfo implements Comparable <SchoolContactInfo>{
      private String name;
      private String phone;

      // Constructor
      public SchoolContactInfo(String Name, String Phone) {
            name = Name;
            phone = Phone;
      }

      public String getName() {
            return name;
      }

      public void setName(String name) {
            this.name = name;
      }

      public String getPhone() {
            return phone;
      }

      public void setPhone(String phone) {
            this.phone = phone;
      }

     public  int compareTo(SchoolContactInfo s){

         return s.getName().compareTo(name);

      }

      abstract  String getMajor();
}

 class ArtStudent extends SchoolContactInfo {
      // constructor
     
     
      public ArtStudent(String name, String phone) {
            super(name, phone);
      }
     
     public String getMajor(){
         return "art";
     }
}

 class MathsStudent extends SchoolContactInfo {
      // constructor
      public MathsStudent(String name, String phone) {
            super(name, phone);
      }
       public String getMajor(){
         return "math";
     }
     
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37727818
If you further force your imafgination and suggest that in order to determine major of the Art student , say you need to determine which subject he spends more hours on, and to deteremine the major of the math student you'll rather need to check the title of his/her most recent report, then you'll exactly have the situation when you need abstract classes, becuase these two implementstions would be absolutely duifferent and specific to particular subclass.
0
 

Author Comment

by:unistudent
ID: 37727893
In my case, just want to output the student name sorted by name and remove duplicate records. as far as I understand from your very clear explaination, I dont think I need to use a abstract class, is't it? please correct me if I am wrong. thanks
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37727900
That's what I wrote you several hours ago.
To remove duplicates and to sort list of contacts is one thing, and has no immediate connection to abstract classes. You told me that you need to show that you know what are abstract classes. Now look in that previous question - I posted the ocde with abstrcat clases for you. Of cousrse there are aboslutely orthonogonal thinsg - abtsract clasess are useful for cerattain situations; sorting and dealing with collections is another topic - is osme systems designs both topics may be relevant; but there is scertainly not connection between them.
0
 

Author Comment

by:unistudent
ID: 37727913
My last question I dont understand is in the main(). why I got compilation eror if

   public static void main (String args[]) {
         ArrayList<Contact> ar = new ArrayList<Contact>();
         ArrayList<Contact> removedDuplicatedRecordArray = new ArrayList<Contact>();

         Contact contact1 = new MathsStudent("Paul", "127654561");
.
.
         ar.add(contact1);
.
.

         AddressBook ab = new AddressBook(ar);  <=== error, saying constructor not defined.. when i defined, not working..

that is the reason I have to pass ar as a parameter. but i dont like this way..
Yan, your explanation is even more easy to understand than what i lecturer explains to us.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37727914
In this  code (the same as I posted in your "Java OO Design... " question
the existence of abstract class SchoolContactInfo1 allows to put both instances of ArtStudent1 and MathsStudent1  into the ArrayList<SchoolContactInfo1>
but it would stilll have been possible if the super class of these two student classes
were not abstract.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class AddressBook {


    ArrayList<SchoolContactInfo1> ar;

    public AddressBook(ArrayList<SchoolContactInfo1> ar){
        this.ar = ar;
    }


    public void printAddressBook() {

        for(SchoolContactInfo1 c : ar){
            System.out.println(c.toString());
        }
    }

    public void removeDuplicates() {
       ArrayList<SchoolContactInfo1> ar1 = new ArrayList<SchoolContactInfo1>();

        for(SchoolContactInfo1 c : ar){
            if(!ar1.contains(c))ar1.add(c);

        }

        ar = ar1;


    }

    public void sortAddressBookByName() {
        Collections.sort(ar, new MyComparator("name"));

    }

     public void sortAddressBookByPhone() {
        Collections.sort(ar, new MyComparator("phone"));

    }



    public static void main(String[] args) {
        ArrayList<SchoolContactInfo1> ar = new ArrayList<SchoolContactInfo1>();

        ArtStudent1 c1 = new ArtStudent1("Peter", "555 333 44 22", new Address("100","First Street","Los Angeles","90345"));
        ArtStudent1 c2 = new ArtStudent1("Mike", "556 333 44 22", new Address("101","Second Street","Los Angeles","90345"));
           MathsStudent1 c3 = new MathsStudent1("Mike", "556 333 44 22", new Address("102","Third Street","Los Angeles","90345"));

        ar.add(c1);
        ar.add(c2);
        ar.add(c3);

                AddressBook ab = new AddressBook(ar);
        System.out.println(" original list of contacts");
           ab.printAddressBook();

          ab.removeDuplicates();

        System.out.println("");

          System.out.println(" list of contacts after removing duplicates ");
         ab.printAddressBook();

        ab.sortAddressBookByName();

            System.out.println("");
         System.out.println(" list of contacts after sorting by name ");

            ab.printAddressBook();

          ab.sortAddressBookByPhone();

         System.out.println(""); 
        System.out.println(" list of contacts after sorting by phone ");

         ab.printAddressBook();



    }



}



abstract class SchoolContactInfo1 implements Comparable <SchoolContactInfo1>  {

    String name;

    String phoneNumber;

    Address address;


    public SchoolContactInfo1(String name, String phoneNumber, Address address){
        this.name = name;
        this.phoneNumber = phoneNumber;
        this.address = address;

    }

     public SchoolContactInfo1(String name, String phoneNumber){
        this.name = name;
        this.phoneNumber = phoneNumber;


    }


    public String toString() {
        String s = " Name: " +  name + ", Phone:  "  + phoneNumber + ",  Address: "  + address.toString();

        return s;

    }

    public String getName() {

           return name;
    }

    public String getPhone() {
        return phoneNumber;
    }


    public boolean equals(Object o){
        if(!(o instanceof SchoolContactInfo1))return false;
        else {
            SchoolContactInfo1 c = (SchoolContactInfo1)o;
            if(c.getName().equals(name) && c.getPhone().equals(phoneNumber))return true;
            else return false;

        }




    }

      public int compareTo(SchoolContactInfo1 c){

          return name.compareTo(c.getName());

    }

    abstract String getMajor();


}

class Address {
    String streetNumber;
    String street;
    String city;
    String zipCode;

    public Address(String streetNumber, String street, String city, String zipCode) {
        this.streetNumber = streetNumber;
        this.street = street;
        this.city = city;
        this.zipCode = zipCode;


    }


    public String toString(){
        String s = streetNumber + "  "  + street + "   " + city + "  " + zipCode;
        return s;

    }




}

class MyComparator implements Comparator<SchoolContactInfo1>{

    String field;

    public MyComparator(String field){
        this.field = field;

    }

    public int compare(SchoolContactInfo1 c1, SchoolContactInfo1 c2){
        if(field.equals("name")) {
            return c1.getName().compareTo(c2.getName());
        } else     return c1.getPhone().compareTo(c2.getPhone());




    }


}


class ArtStudent1 extends SchoolContactInfo1 {
      // constructor


      public ArtStudent1 (String name, String phone) {
            super(name, phone);
      }
     public ArtStudent1 (String name, String phone, Address address) {
            super(name, phone, address);
      }


     public String getMajor(){
         return "art";
     }
}

 class MathsStudent1 extends SchoolContactInfo1 {
      // constructor
      public MathsStudent1(String name, String phone) {
            super(name, phone);
      }
        public MathsStudent1 (String name, String phone, Address address) {
            super(name, phone, address);
      }
       public String getMajor(){
         return "math";
     }

}
                                            

Open in new window

0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 47

Expert Comment

by:for_yan
ID: 37727925
You usually really need to devise abstract class, when there is a need of this method which would in fact be implemented in all real life subclasses, whereas implementations will be different, and there is no general implementation becuase in reality this general object does not exist as a general entity, it only exists in one of several specific incarnations.
just think about my example above about abstract Shape on the one hand, and real Square, Circle, Rectangle - we cna claculate area and perimeter for each of them but w cannot do it as easily for general Shape and in all real cases we'll encounter with some specific incarbnation fo Shape, not with its general idea
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37727931
I don't know why

AddressBook ab = new AddressBook(ar);
it causes error for you.

probably you messed with this code there, thsi is weere this constructor is defined:


  public AddressBook(ArrayList<SchoolContactInfo1> ar){
        this.ar = ar;
    }

You see it all works in my code - look at it, and before you amke any single change understadn why you are making it and immediately after you made the change
compile and test

Once you have  working code - all changes should be made very much stepwise - you'll
save your self a lot of time if you follow this rule
0
 

Author Comment

by:unistudent
ID: 37727942
Look like

public class AddressBook {

      ArrayList<Contact> ar;  <=== look like this one never use. but your example works very well. I dont understand */

/* I add the following constructor
      public AddressBook(ArrayList<Contact> ar2) {
            // TODO Auto-generated constructor stub
      }
0
 
LVL 47

Accepted Solution

by:
for_yan earned 0 total points
ID: 37727958
You cannot add such constructor
  public AddressBook(ArrayList<Contact> ar2) {
            // TODO Auto-generated constructor stub
      }

each class can have only one constructor with the same numebr oand order of arguments, so
you cannot have

this contructor

  public AddressBook(ArrayList<Contact> ar2) {
           
      }

and this constructor:

  public AddressBook(ArrayList<Contact> ar) {
           this.ar = ar;
      }

becuase they bothe have one argument of type ArrayList<Contact>
Only one such contructor is allowed.

So if you place both of them in one class - you'll have compilation error

and this constructor which I had is critical - it needs to be there:
  public AddressBook(ArrayList<Contact> ar) {
           this.ar = ar;
      }

when you are changing you should be very careful and also realize why you are changin.
What was the point fo adding thos second constructor (which can only cayuse compilation eroor) ?
0
 

Author Comment

by:unistudent
ID: 37727966
Yes. I take your advise seriously. thanks. I just find out. my mistakes..
0
 

Author Comment

by:unistudent
ID: 37727970
now they all work very fine. thanks
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37727973
Good!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now