Friday, 22 January 2016

Java class1

1. Overriding

* Child

public class Child extends Parent {
  private void doSomething() {}

}

* Parent

public class Parent {
  public void doSomething() {}

}


* UseBoth

public class UseBoth {
  public void doOtherThing() {
    Parent p1 = new Parent();
    Parent p2 = new Child(); // illegal
    p1.doSomething();
    p2.doSomething();
  }

}


2.  Codes ID :-

*  Employee

public class Employee {

  private String name;
  private MyDate birthDate;
  private float  salary;

  // Constructor
  public Employee(String name, MyDate DoB, float salary) {
    this.name = name;
    this.birthDate = DoB;
    this.salary = salary;
  }

  public String getDetails() {
    return "Name: " + name + "\nSalary: " + salary
           + "\nBirth Date: " + birthDate;
  }
}


*  Manager

public class Manager extends Employee {
  private String department;

  public Manager(String name, MyDate DoB,
float salary, String dept) {
    super(name, DoB, salary);
    this.department = dept;
  }

  public String getDetail() {
    return super.getDetails() + "\nDepartment: " + department;
  }
}


*  MyDate

public class MyDate {
  private int day;
  private int month;
  private int year;

  public MyDate(int day, int month, int year) {
    this.day   = day;
    this.month = month;
    this.year  = year;
  }

  public boolean equals(Object o) {
    boolean result = false;
    if ( (o != null) && (o instanceof MyDate) ) {
      MyDate d = (MyDate) o;
      if ( (day == d.day) && (month == d.month)
  && (year == d.year) ) {
        result = true;
      }
    }
    return result;
  }

  public int hashCode() {
    return (day ^ month ^ year);
  }
}


*  TestEquals


public class TestEquals {
  public static void main(String[] args) {
    MyDate  date1 = new MyDate(14, 3, 1976);
    MyDate  date2 = new MyDate(14, 3, 1976);

    if ( date1 == date2 ) {
      System.out.println("date1 is identical to date2");
    } else {
      System.out.println("date1 is not identical to date2");
    }

    if ( date1.equals(date2) ) {
      System.out.println("date1 is equal to date2");
    } else {
      System.out.println("date1 is not equal to date2");
    }

    System.out.println("set date2 = date1;");
    date2 = date1;

    if ( date1 == date2 ) {
      System.out.println("date1 is identical to date2");
    } else {
      System.out.println("date1 is not identical to date2");
    }
  }
}


Code :-   https://drive.google.com/open?id=0B08RKBSts8D8T3BWTGpyQmNJeG8

No comments:

Post a Comment