Classes/Objects  «Prev  Next»


Lesson 1

Classes, Interfaces, and Objects in Java

One of Java's strengths is its excellent support for object-oriented programming. This support is provided through classes and interfaces, which are the building blocks of all Java programs. The ability to effectively use classes and interfaces is an essential Java programming skill. The certification exam recognizes the importance of class and interface fundamentals and contains a number of questions that test your knowledge of them. This module reviews these topics and identifies any important points that you should know in preparation for the exam. In Java what is the relationship between Classes, Interfaces and Objects?
In Java, classes, interfaces, and objects are fundamental components of the object-oriented programming paradigm. They each play distinct roles and have specific relationships with one another. Here’s an explanation of their relationship:
Classes
  1. Definition: A class is a blueprint for creating objects. It defines the data (fields) and behaviors (methods) that the objects created from the class will have.
  2. Components:
    • Fields: Variables that hold the state of an object.
    • Methods: Functions that define the behavior of an object.
  3. Example:
    public class Animal {
       String name;
       int age;
    
       void makeSound() {
    	   System.out.println("Animal sound");
       }
    }
    


Interfaces
  1. Definition: An interface is a reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors.
  2. Purpose: Interfaces provide a way to achieve abstraction and multiple inheritance in Java. They define a contract that implementing classes must fulfill.
  3. Components:
    • Method Signatures: Abstract methods that implementing classes must override.
    • Default Methods: Methods with default implementation.
    • Static Methods: Methods that belong to the interface itself.
  4. Example:
    public interface AnimalInterface {
       void eat();
       void sleep();
    }
    

Objects
  1. Definition: An object is an instance of a class. It is created based on the structure and behavior defined by the class.
  2. Components:
    • State: Represented by the object's fields (variables).
    • Behavior: Represented by the object's methods (functions).
  3. Example:
    public class Dog extends Animal implements AnimalInterface {
       void makeSound() {
    	   System.out.println("Bark");
       }
    
       public void eat() {
    	   System.out.println("Dog is eating");
       }
    
       public void sleep() {
    	   System.out.println("Dog is sleeping");
       }
    }
    
    public class Main {
       public static void main(String[] args) {
    	   Dog myDog = new Dog(); // Creating an object
    	   myDog.name = "Buddy";
    	   myDog.age = 5;
    	   myDog.makeSound();
    	   myDog.eat();
    	   myDog.sleep();
       }
    }
    

Relationship Between Classes, Interfaces, and Objects
  1. Classes and Objects:
    • Classes define the structure and behavior that objects will have.
    • Objects are instances of classes, created using the `new` keyword.
  2. Classes and Interfaces:
    • A class can implement one or more interfaces, meaning it agrees to fulfill the contract defined by those interfaces.
    • When a class implements an interface, it must provide concrete implementations for all abstract methods declared in the interface.
  3. Objects and Interfaces:
    • Objects created from classes that implement interfaces can be referenced using the interface type.
    • This allows for polymorphism, where a single interface type can refer to objects of different classes implementing that interface.
  4. Example Relationship:
    Animal animal1 = new Dog(); 
    AnimalInterface animalInterface = new Dog(); // animalInterface is an object of type Dog, referenced as AnimalInterface
    animalInterface.eat();
    animalInterface.sleep();
    
Summary
  1. Classes provide the blueprint for creating objects.
  2. Objects are instances of classes and represent specific entities with state and behavior.
  3. Interfaces define contracts that classes can implement, allowing for abstraction and polymorphism.
  4. Classes can implement multiple interfaces, and objects of these classes can be referenced using the interface type to leverage polymorphism.


Module Objectives

This module will review your knowledge of Java classes and interfaces, provide examples of their use, and help you to satisfy the following exam objectives:
  1. Declare classes and inner classes, making appropriate use of all permitted modifiers (such as public, final, static, abstract, and so on).
  2. Identify correctly constructed class declarations (of all forms, including inner classes), interface declarations, and implementations.
  3. State the benefits of encapsulation in object-oriented design, and write code that implements tightly encapsulated classes and the relationships "is a" and "has a."
  4. Write code to construct instances of any concrete class, including normal top-level classes, inner classes, static inner classes, and anonymous inner classes.
  5. For a given class, determine if a default constructor will be created, and if so, state the prototype of that constructor.


Classes and Interfaces

Classes and interfaces are building blocks of an application. Efficient and effective class design makes a significant impact on the overall application design. Imagine if, while designing your classes, you did not consider effective packaging, correct overloaded or overridden methods, or access protection you might lose on extensibility, flexibility, and usability of your classes. For example, if you did not override methods hashCode() and equals() correctly in your classes, your seemingly equal objects might not be considered equal by collection classes like HashSet or HashMap. Imagine if you did not use the right access modifiers to protect your classes and their members, they could be subject to unwanted manipulation by other classes from the same or different packages. The creation of overloaded methods is another domain, which is an important class design decision. It eases instance creation and use of methods. Class design decisions require an insight into understanding correct and appropriate implementation practices. When armed with adequate information you willbe able to select the best practices and approach to designing your classes. The topics covered in this chapter will help you design better classes by taking you through multiple examples. This module covers
  1. Access modifiers
  2. Method overloading
  3. Method overriding
  4. Virtual method invocation
  5. Use of the instanceof operator and casting
  6. Override methods from class Object to improve the functionality of your class
  7. How to create packages and use classes from other packages


Anonymous Inner Class Question:

Anonymous inner classes always extend directly from the Object class.
  1. True
  2. False


Answer: b
Explanation:
When you create an anonymous class for an interface then it extends from Object. For example,
button.addActionListener( new ActionListener() { 
 public void actionPerformed(ActionEvent ae) { } 
});

But if you make an anonymous class from another class then it extends from that class. For example, consider the following class:
class MyListener implements ActionListener{
 public void actionPerformed(ActionEvent ae){System.out.println("MyListener class");}
}
button.addActionListener( new MyListener() {
 public void actionPerformed(ActionEvent ae) { 
  System.out.println("Anonymous Listener class"); }
} );
Here the anonymous class actually extends from the MyListener class and successfully overrides the actionPerformed() method.

SEMrush Software