130 likes | 266 Views
Class vs Abstract vs Interface. Class. 100% concrete (full defined) data type All methods are fully implemented May be directly instantiated (created) but invoking one of its constructors. extends Parent – Child Classes . A class (fully functioning) may have sub-classes.
E N D
Class • 100% concrete (full defined) data type • All methods are fully implemented • May be directly instantiated (created) but invoking one of its constructors
extends Parent – Child Classes • A class (fully functioning) may have sub-classes. • The subclass inherits functionality from the parent
Student is the parent class HighSchoolStudent is-A student HighSchoolStudent inherits from Student Notice that HighSchoolStudent does NOT have a name field or methods related to name. These things are inherited and therefore you do not repeat them in the child class. Is-A
c.getName() will work because HighSchoolStudent inherited that method from Student
b is a reference to a Student object – when you output b it looks to see what type of Student is it actually referencing and calls the toString of the HighSchoolStudent class.
Abstract • Incomplete class definition (conceptual) • May include fully implemented methods • May include unimplemented abstract methods • Cannot be directly instantiated • Subclasses of an abstract class must: • Implement all the abstract methods • Or • Be declared as abstract also
This class is abstract because there is not a default area or perimeter formula
Both Square and Circle inherit name from the Shape class. Both Square and Circle implement getArea() and getPerimeter() with the correct formula.
The output is calling the toString for each object. In the toString the getArea() and getPerimeter() methods are called. Java uses dynamic binding to call the correct getArea() method – meaning if it is a Circle Java will call Circle’s getArea() and if it is a Square Java will call Square’s getArea()
You cannot instantiate a Shape because it is abstract s.getArea() would not work because getArea is abstract in the Shape class.
Interface • 100% abstract (conceptual) data type • Declares what operations (functionality) the type will have • Doesn’t define any operations (no implemented methods) • Only abstract methods • Cannot be directly instantiated (NO CONSTRUCTOR)