Docsity

Quick Learning Content, Summaries of Computer Science

Toggle sidebar
bg1
CSE Core Object Oriented Programming
Java Handout 07 of 20
Abstraction and Interfaces
Use abstraction to expose the operations callers need. An interface defines a type for related behavior. An abstract
class can share state and concrete methods while leaving selected methods for subclasses.
Concept Review
• A concrete class implements the required abstract methods of its interfaces.
• An implementation of a public interface method must be public.
• Instantiate a concrete subclass to use behavior defined by an abstract class.
Worked Java Example
Define a common contract for shapes. Save as Main.java.
public class Main {
static interface Measurable {
int area();
}
static abstract class Shape implements Measurable {
String describe() { return "Area = " + area(); }
}
static class Square extends Shape {
private final int side;
Square(int side) { this.side = side; }
public int area() { return side * side; }
}
public static void main(String[] args) {
Shape shape = new Square(4);
System.out.println(shape.describe());
}
}
Expected output Area = 16
Practice and Self Check
Practice Add a Rectangle subclass that accepts width and height. Check that a 3 by 5 rectangle prints Area = 15.
Quick check Which method does Shape share with subclasses? Check: describe().

Partial preview of the text

Download Quick Learning Content and more Summaries Computer Science in PDF only on Docsity!

CSE Core Object Oriented Programming

Java Handout 07 of 20

Abstraction and Interfaces

Use abstraction to expose the operations callers need. An interface defines a type for related behavior. An abstract class can share state and concrete methods while leaving selected methods for subclasses. Concept Review

  • A concrete class implements the required abstract methods of its interfaces.
  • An implementation of a public interface method must be public.
  • Instantiate a concrete subclass to use behavior defined by an abstract class. Worked Java Example Define a common contract for shapes. Save as Main.java. public class Main { static interface Measurable { int area(); } static abstract class Shape implements Measurable { String describe() { return "Area = " + area(); } } static class Square extends Shape { private final int side; Square(int side) { this.side = side; } public int area() { return side * side; } } public static void main(String[] args) { Shape shape = new Square(4); System.out.println(shape.describe()); } } Expected output Area = 16 Practice and Self Check Practice Add a Rectangle subclass that accepts width and height. Check that a 3 by 5 rectangle prints Area = 15. Quick check Which method does Shape share with subclasses? Check: describe().