lecture7
java1-lecture7
Lab6
Lab6 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (3~4장)를 넣고 JAVA20_Lab6_분반_학번_이름.zip 압축한 후 제출 (Due by 5/21)
Lab6 abstract class vs inheritance
java1-lab6
Comparable & Comparator Interface
import java.util.*;
class Person implements Comparable<Person> {
private static int count = 0; // static (class) field
protected String name; // instance field
protected int age; // instance field
public Person() {
//System.out.println("Person Constructor"); // this("", 0); error: call to this must be first statemenht in constructor
this("", 0);
}
public Person(String name, int age) {
count++;
this.name = name;
this.age = age;
}
public Person(Person other) {
this(other.name, other.age);
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void set(String name, int age) {
this.name = name;
this.age = age;
}
public void set(Person other) {
this.name = other.name;
this.age = other.age;
}
public Person clone() {
Person p = new Person(this.name, this.age);
return p;
}
@Override
public boolean equals(Object other) { // Object.equals overriding
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}
@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}
public boolean canEqual(Object other) {
return (other instanceof Person);
}
@Override
public String toString() { // Object.toString() overriding
return "Person Name: " + name + " Age: " + age;
}
public void print() { // instance methods
System.out.println("Person Name: " + name + " Age: " + age);
}
public static void printCount() { // static (class) methods
System.out.println("Person Count: " + count);
}
public static int getCount() { // static (class) methods
return count;
}
public static void setCount(int value) { // static (class) methods
count = value;
}
public int compareTo(Person other) {
String thisName = this.getName().toUpperCase();
String otherName = ((Person)other).getName().toUpperCase();
//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}
public static Comparator<Person> AgeComparator = new Comparator<Person>() {
public int compare(Person p1, Person p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();
//ascending order
return age1 – age2;
//descending order
//return age2 – age1;
}
};
}
///////////////////////////////////////////////////////////////////////////////////////
class Student extends Person {
private static int count = 0; // static (class) field
protected int id;
public Student() {
id = 5208;
}
public Student(String name, int age, int id) {
super(name, age);
this.id = id;
count++;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public void set(String name, int age, int id) {
super.set(name, age);
this.id = id;
}
public void set(String name, int age) {
super.set(name, age);
}
public void set(Student other) {
this.set(other.name, other.age, other.id);
}
public void set(Person other) {
if (other instanceof Person)
super.set(other);
else
this.set((Student)other);
}
public Student clone() {
Student s = new Student(this.name, this.age, this.id);
return s;
}
@Override
public boolean equals(Object other) { // Object.equals overriding
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}
@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}
public boolean canEqual(Object other) {
return (other instanceof Student);
}
@Override
public String toString() { // Object.toString() overriding
return "Student Name: " + name + " Age: " + age + " ID: " + id;
}
public void superPrint() {
super.print();
}
public void print() { // Person.print() method overriding
System.out.println("Student Name: " + name + " Age: " + age + " ID: " + id);
}
public static void printCount() { // static (class) methods
System.out.println("Student Count: " + count);
}
public static int getCount() { // static (class) methods
return count;
}
public static void setCount(int value) { // static (class) methods
count = value;
}
public int compareTo(Student other) {
String thisName = this.getName().toUpperCase();
String otherName = ((Student)other).getName().toUpperCase();
//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}
public static Comparator<Student> AgeComparator = new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();
//ascending order
return age1 – age2;
//descending order
//return age2 – age1;
}
};
public static Comparator<Student> IDComparator = new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int id1 = p1.getID();
int id2 = p2.getID();
//ascending order
return id1 – id2;
//descending order
//return id2 – id1;
}
};
}
class PersonStudentTest {
public static void print(Object[] array) {
for(Object o : array) {
System.out.println(o);
}
}
public static void main(String[] args) {
///////////////////////////////////////////////////////////////////////
Student[] sList = new Student[3];
sList[0] = new Student("Kevin", 0, 222);
sList[1] = new Student("Jason", 1, 333);
sList[2] = new Student("John", 2, 111);
System.out.println("STUDENT SORT BY NAME (DEFAULT)!!!");
Arrays.sort(sList);
print(sList);
System.out.println("STUDENT SORT by AGE!!!");
Arrays.sort(sList, Student.AgeComparator);
print(sList);
System.out.println("STUDENT SORT by ID!!!");
Arrays.sort(sList, Student.IDComparator);
print(sList);
///////////////////////////////////////////////////////////////////////
Student[] sList2 = new Student[3];
sList2[0] = new Student("Kevin", 0, 222);
sList2[1] = new Student("Jason", 1, 333);
sList2[2] = new Student("John", 2, 111);
System.out.println("STUDENT SORT BY NAME (anonymous method)!!!");
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getName().toUpperCase().compareTo(s2.getName().toUpperCase());
}
});
print(sList2);
System.out.println("STUDENT SORT by AGE (anonymous method)!!!");
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getAge() – s2.getAge();
}
});
print(sList2);
System.out.println("STUDENT SORT by ID (anonymous method)!!!");
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getID() – s2.getID();
}
});
print(sList2);
///////////////////////////////////////////////////////////////////////
Student[] sList3 = sList2;
System.out.println("STUDENT SORT BY NAME (lambda)!!!");
Arrays.sort(sList3, (Student ss1, Student ss2) ->
ss1.getName().compareTo(ss2.getName())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));
System.out.println("STUDENT SORT by AGE (lambda)!!!");
Arrays.sort(sList3, (Student ss1, Student ss2) ->
Integer.compare(ss1.getAge(), ss2.getAge())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));
System.out.println("STUDENT SORT by ID (lambda)!!!");
Arrays.sort(sList3, (Student ss1, Student ss2) ->
Integer.compare(ss1.getID(), ss2.getID())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));
///////////////////////////////////////////////////////////////////////
List<Student> sList4 = new ArrayList<Student>();
sList4.add(new Student("Kevin", 0, 222));
sList4.add(new Student("Jason", 1, 333));
sList4.add(new Student("John", 2, 111));
System.out.println("STUDENTLIST SORT BY NAME (lambda)!!!");
sList4.sort((Student ss1, Student ss2) ->
ss1.getName().compareTo(ss2.getName())
);
sList4.forEach((s) -> System.out.println(s));
System.out.println("STUDENTLIST SORT by AGE (lambda)!!!");
sList4.sort((Student ss1, Student ss2) ->
ss1.getAge() – ss2.getAge()
);
sList4.forEach((s) -> System.out.println(s));
System.out.println("STUDENTLIST SORT by ID (lambda)!!!");
sList4.sort((Student ss1, Student ss2) ->
ss1.getID() – ss2.getID()
);
sList4.forEach((s) -> System.out.println(s));
}
}
Shape Polymorphism with Interface
Shape 추상클래스 has-a ShapeType, ShapeColor, ShapeRect
Shape 추상클래스를 상속받은 Triangle, Rectangle, Square, Circle 클래스는 추상메소드인 void area()를 반드시 구현하였다.
Shape 추상클래스는 Moveable, Scalable 인터페이스를 상속하여 추상메소드인 Moveable 인터페이스의 void move(int, int)와 Scalable 인터페이스의 void scale(int)를 구현하였다.
lecture6
lecture6
java1-lecture6
Midterm Homework
Midterm Homework
2019 Java1 중간고사 문제를 풀어본다.
java19-1-midterm-answer
2019 Java1 중간고사 예제 코드 작성 + 본인 예제 프로그램 (문제 하나당 비슷한 예제) + 문제풀이는 코드에 주석으로 작성 (1.6 그림그리기는 생략)
2.5 오류가 나는 이유를 설명하시고, 그와 비슷한 다른 예시를 본인이 더 만들어서 설명하세요.
문제 풀이 답변을 코드 작성과 함께 주석으로 적어주시면됩니다. 당연히 제가 준 답을 똑같이 적으면 안됩니다! 본인이 문제의 내용을 이해하고 본인의 말로 “주석”으로 달아주시면 됩니다.
출석체크 및 온라인활동: Java20_Midterm_분반#_학번_이름.zip을 kpark0527@gmail.com으로 제출 (due by 5/14 11:59 pm)
HW Grading Policy
HW6(Lab5-2)부터 채점 기준
보고서는 본인 코드 구현을 중심으로 설명할 것. 클래스/메소드 기능명세가 아니라 본인이 어떤 방식으로 구현/시도했는지 무엇을 배웠는지 등. 클래스/메소드 기능명세는 소스코드에 주석(comment)으로 작성요망.
보고서, 소스코드, 이클립스프로젝트 파일 폴더 전체가 없음 -7 (다른 IDE 사용자는 bin과 src디렉토리 첨부요) (숙제 10점 중)
소스코드 컴파일 에러 -7
코드 실행 에러 및 잘못된 결과 -1
소스 코드에 주석 없음 -3
Your Code 없음 -1
소스코드 첫부분에 Lab이름, 날짜, 본인이름 적을것 -1
보고서표지에 Lab번호, 분반번호, 제출일, 학번, 이름을 적을것 -1
보고서 제출안함 -10
보고서에 내용을 작성하지 않고 소스코드 사진캡쳐해서 붙여넣기 -3 (“소스코드 사진캡쳐만” 제출하는 경우)
보고서에 소스코드 복사해서 붙여넣기 -3
보고서에 소스코드 내용을 작성하지 않고 다른 것 적기 -3
보고서에 Your Code 설명 없음 -1
보고서에 실행결과창 없음 -1 (실행결과 캡쳐사진)
보고서파일포멧 (hwp/doc(x)/pdf 아닐시) -10
Why doesn’t Java allow overriding of static methods
https://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods
Yes. Practically Java allows overriding static method, and No theoretically if you Override a static method in Java then it will compile and run smoothly but it will lose Polymorphism which is the basic property of Java. You will Read Everywhere that it is not possible to try yourself compiling and running. you will get your answer. e.g. If you Have Class Animal and a static method eat() and you Override that static method in its Subclass lets called it Dog. Then when wherever you Assign a Dog object to an Animal Reference and call eat() according to Java Dog’s eat() should have been called but in static Overriding Animals’ eat() will Be Called.
class Animal {
public static void eat() {
System.out.println(“Animal Eating”);
}
}
class Dog extends Animal{
public static void eat() {
System.out.println(“Dog Eating”);
}
}
class Test {
public static void main(String args[]) {
Animal obj= new Dog();//Dog object in animal
obj.eat(); //should call dog’s eat but it didn’t
}
}
Output Animal Eating
According to Polymorphism Principle of Java, the Output Should be Dog Eating.
But the result was different because to support Polymorphism Java uses Late Binding that means methods are called only at the run-time but not in the case of static methods. In static methods compiler calls methods at the compile time rather than the run-time, so we get methods according to the reference and not according to the object a reference a containing that’s why You can say Practically it supports static overring but theoretically, it doesn’t.
Abstract Class & Abstract Method & Polymorphism
Abstract Class (추상 클래스)는 하나 이상의 abstract method(추상메소드)를 가지거나, 추상메소드가 없지만 abstract으로 선언한 클래스. 추상클래스는 객체를 생성할 수 없다.
Abstract Method (추상 메소드)는 선언은 되어 있으나 구현 내용이 없는 메소드이다.
추상클래스를 상속받은 하위클래스는 반드시 추상 메소드를 재정의(method override) 구현해야한다.
Polymorphism (다형성)은 프로그램 실행(run-time execution)시 형(type)이 변화되는 객체.
다형성에 따라서, 클래스 상속관계(Inheritance)에서 메소드 재정의(Method overriding)된 것이 동적 바인딩(dynamic binding)으로 호출되었을 시, 해당 객체에 맞는 재정의된 메소드가 호출되는 것이다.
Shape 추상클래스 has-a ShapeType, ShapeColor, ShapeRect
Shape 추상클래스를 상속받은 Triangle, Rectangle, Square, Circle 클래스는 추상메소드인 area()를 반드시 구현해야한다.
https://www.cs.usfca.edu/~wolber/SoftwareDev/OO/abstractInterfacesIntro.htm
Static vs Instance Initializer Block
Static Initializer Block
- class 로딩 시 호출
- instance variable이나 method에 접근 못함
- static variable 초기화에 사용
public class StaticIntializerBlockTest {
private static int id = 5;
static {
if (id <10) id = 20;
else id = 100;
}
public static int getId() {
return id;
}
public static void print() {
System.out.println("StaticIntializerBlockTest.id=" + getId());
}
}
public class StaticInstanceInitializerBlockTest {
public static void main(String[] args) {
StaticIntializerBlockTest.print();
}
}
StaticIntializerBlockTest.id=20 // static block 이 호출되면서 20으로 셋팅
Instance Initializer Block
- 객체 생성시 호출
- super 생성자 이후에 실행하고, 생성자보다 먼저 실행
- instance variable이나 method에 접근 가능
- 모든 생성자의 공통 부분을 instance initializer block에 넣어줌
class InstanceInitializerBlockSuper {
public InstanceInitializerBlockSuper() {
System.out.println("InstanceInitializerBlockSuper");
}
}
public class InstanceInitializerBlockTest extends InstanceInitializerBlockSuper {
private int id = 5;
{
if (id <10) id = 20;
else id = 100;
}
public InstanceInitializerBlockTest() {
System.out.println("InstanceInitializerBlockTest.id=" + this.id);
}
public InstanceInitializerBlockTest(int id) {
System.out.println(“InstanceInitializerBlockTest.id=" + this.id);
this.id = id;
}
public int getId() {
return id;
}
public void print() {
System.out.println("StaticIntializerBlockTest.id=" + getId());
}
}
public class StaticInstanceInitializerBlockTest {
public static void main(String[] args) {
InstanceInitializerBlockTest i = new InstanceInitializerBlockTest();
i.print();
i = new InstanceInitializerBlockTest(30);
i.print();
}
}
InstanceInitializerBlockSuper // super 생성자 이후에 실행
InstanceInitializerBlockTest.id=20 // instance block 호출되면서 20으로 셋팅
id=20
InstanceInitializerBlockSuper // super 생성자 이후에 실행
InstanceInitializerBlockTest.id=20 // instance block 호출되면서 20으로 셋팅된후 this.id = id를 통해서 30으로 셋팅
id=30
https://stackoverflow.com/questions/12550135/static-block-vs-initializer-block-in-java