OOPS Features in Java PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document explains concepts and practical examples in Java's Object-Oriented Programming Structure, focusing on inheritance, subclass, and superclass. The document describes the use of the "super" keyword and offers a "real-world" example of an animal hierarchy. This is likely an educational teaching document intended to help students learn Java.
Full Transcript
OOPS Features in Java Inheritance Using inheritance, we can create a general class that defines characteristics common to a set of related entities. This class can then be inherited by other, more specific classes, each adding those characteristics that are unique to it. A class that is inh...
OOPS Features in Java Inheritance Using inheritance, we can create a general class that defines characteristics common to a set of related entities. This class can then be inherited by other, more specific classes, each adding those characteristics that are unique to it. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. Subclass inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements. To inherit a class, we use the extends keyword. Being a superclass for a subclass does not mean that the superclass cannot be used by itself, i.e. we can create object of the superclass. We can specify only one superclass for any subclass that we create. Java does not support the inheritance of multiple superclasses into a single subclass. No class can be a superclass of itself. Inheritance A subclass includes all of the members of its superclass but it cannot access those members of the superclass that have been declared as private. This means a class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses. A major advantage of inheritance is that once you have created a superclass that defines the attributes common to a set of objects, it can be used to create any number of more specific subclasses (precisely tailored to its own classification). Inheritance - example class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } Inheritance - example class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); // The subclass has access to all public members of its superclass. subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); }} Superclass Variable Referencing Subclass Object A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass. A reference variable of a superclass can hold an object of its subclass. This is possible because a subclass inherits all the properties and behaviors (methods) of its superclass, making it a valid reference. However, when using the superclass reference, you can only call the methods and access the fields that are defined in the superclass (unless overridden in the subclass). It is important to note that only methods available in the superclass can be called unless overridden in the subclass. The specific methods and variables introduced in the subclass will not be accessible directly through the superclass reference. This mechanism allows for flexibility in the design, where the exact type of object is determined at runtime, but you can still work with a common reference type to interact with objects of different subclasses. Note: It is important to understand that it is the type of the reference variable—not the type of the object that it refers to—that determines what members can be accessed. Example: class Animal { public void sound() { System.out.println("Animal makes a sound"); }} class Dog extends Animal { public void sound() { System.out.println("Dog barks"); } } class Cat extends Animal { public void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { Animal myAnimal; myanimal = new Animal(); myanimal.sound(); myAnimal = new Dog(); myAnimal.sound(); myAnimal = new Cat(); myAnimal.sound(); }} Using Super Sometimes we want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Super keyword allows a subclass to refer to its immediate superclass. Super has two general forms: 1. The first calls the superclass’ constructor. 2. The second is used to access a member of the superclass that has been hidden by a member of a subclass. Using Super to call Parent class Constructor A subclass can call a constructor defined by its superclass by use of the following form of super: super(arg-list); Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor. Since constructors can be overloaded, super( ) can be called using any form defined by the superclass. The constructor executed will be the one that matches the arguments. Using Super to call Parent class Constructor - Example class Box { class BoxWeight extends class DemoSuper { private double width; Box { public static void private double height; double weight; main(String args[]) { private double depth; BoxWeight(BoxWeight ob) BoxWeight mybox1 = new Box(Box ob) { { BoxWeight(10, 20, 15, width = ob.width; super(ob); 34.3); height = ob.height; weight = ob.weight; BoxWeight myclone = depth = ob.depth; } new BoxWeight(mybox1); } BoxWeight(double w,... Box(double w, double h, double d) double h, double d,... { double m) { width = w; super(w, h, d); height = h; weight = m; depth = d; }} }} Using Super to call Parent class Constructor - Example class AgeNotValidException extends Exception { public AgeNotValidException(String message) { super(message); } } public class ValidateAge { public static void checkAge(int age) throws AgeNotValidException { if (age < 18) throw new AgeNotValidException("Age is not valid, must be 18 or older."); } else { System.out.println("Age is valid."); } } public static void main(String[] args) { try { // Check if the age is valid checkAge(16); } catch (AgeNotValidException e) { System.out.println("Caught the exception: " + e.getMessage()); } System.out.println("Now the program continues from here…"); int x=10; System.out.println("X = "+x); }} Using Super to access hidden member of Parent class The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Example - class A { int i;} class B extends A { int i; B(int a, int b) { super.i = a; i = b;} void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); }} class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); }} Arrays An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. One Dimensional Arrays: The general form of a one-dimensional array declaration is type var-name[ ]; Here, type declares the base type of the array. For example: int student_age[ ]; With this declaration, no array actually exists. In fact, the value of student_age is set to null, which represents an array with no value. To link student_age with an actual, physical array of integers, we must allocate one using new operator and assign it to student_age. Arrays – One Dimensional The general form of new as it applies to one-dimensional arrays is as follows: var-name = new type[size]; For example: student_age = new int; After this statement executes, student_age will refer to an array of 10 integers and all elements in the array will be initialized to zero. We can do it in a single step also as follows: int student_age[] = new int; There’s an alternative way to declare an array as shown below: type[ ] var-name; For example: int[ ] student_age; This alternative declaration form offers convenience when declaring several arrays at the same time. int[ ] age, height, weight; Arrays – Initialization Arrays can be initialized when they are declared. An array initializer is a list of comma-separated expressions surrounded by curly braces. The commas separate the values of the array elements. The array will automatically be created large enough to hold the number of elements you specify in the array initializer. There is no need to use new in this case. For example: int student_age[] = { 18, 18, 17, 15, 16, 17, 15, 18, 19, 14 }; Arrays – Example Program // Average an array of values. class Average { public static void main(String args[]) { double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double result = 0; int i; for(i=0; i