Link to home
Start Free TrialLog in
Avatar of unistudent
unistudent

asked on

Java - confuse using abstract class and class

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
=============================================================
Avatar of for_yan
for_yan
Flag of United States of America image

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

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.
Avatar of unistudent
unistudent

ASKER

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
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.
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.
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

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
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
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
      }
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes. I take your advise seriously. thanks. I just find out. my mistakes..
now they all work very fine. thanks
Good!