Sie sind auf Seite 1von 40

Chapter 2

Passing array to function


• You can pass arrays to a method just like normal variables. When we
pass an array to a method as an argument, actually the address of the
array in the memory is passed (reference). Therefore, any changes to
this array in the method will affect the array.
• Suppose we have two methods min() and max() which accepts an
array and these methods calculates the minimum and maximum
values of the given array respectively:
• import java.util.Scanner; •    public static void main(String args[]) {
• public class ArraysToMethod { •       Scanner sc = new Scanner(System.in);
•       System.out.println("Enter the size of the array
•    public int max(int [] array) { that is to be created::");
•       int max = 0; •       int size = sc.nextInt();
•       for(int i=0; i<array.length; i++ ) { •       int[] myArray = new int[size];
•          if(array[i]>max) { •       System.out.println("Enter the elements of the
array ::");
•             max = array[i]; •       for(int i=0; i<size; i++) {
•          }   } •          myArray[i] = sc.nextInt();
•       return max;   } •   }
•    public int min(int [] array) { •       ArraysToMethod m = new ArraysToMethod();
•       System.out.println("Maximum value in the
•       int min = array[0]; array is::"+m.max(myArray));
•       for(int i = 0; i<array.length; i++ ) { •       System.out.println("Minimum value in the
•          if(array[i]<min) { array is::"+m.min(myArray));
•    }
•             min = array[i];}   }
•}
•       return min;   }
Inheritance
• Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. It is an important
part of OOPs (Object Oriented programming system).
• The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing
class, you can reuse methods and fields of the parent class. Moreover,
you can add new methods and fields in your current class also.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
• Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
• Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.
Single Inheritance and allied
nomenclature
Multi level inheritance
Hierarchial inheritance
Multiple Inheritance
Hybrid Inheritance
Extend Keyword.
• The extends keyword extends a class (indicates that a class is
inherited from another class).

• In Java, it is possible to inherit attributes and methods from one class


to another. We group the "inheritance concept" into two categories:
• subclass (child) - the class that inherits from another class
• superclass (parent) - the class being inherited from

• To inherit from a class, use the extends keyword.


Extend - Example
• class Vehicle {
  protected String brand = "Ford";         // Vehicle attribute
  public void honk() {                     // Vehicle method
    System.out.println("Tuut, tuut!");
  }
}

class Car extends Vehicle {
  private String modelName = "Mustang";    // Car attribute
  public static void main(String[] args) {

    // Create a myCar object


    Car myCar = new Car();

    // Call the honk() method (from the Vehicle class) on the myCar object
    myCar.honk();

    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
    System.out.println(myCar.brand + " " + myCar.modelName); 
 }
}
Extend constructors - super
• The super keyword in java is a reference variable that is used to refer
parent class objects.
• 1. Use of super with variables: This scenario occurs when a derived class and
base class has same data members. In that case there is a possibility of
ambiguity for the JVM
Example
• /* Base class vehicle */ • /* Driver program to test */
• class Vehicle
•{
• class Test
• int maxSpeed = 120; •{
•} • public static void main(String[] args)
• /* sub class Car extending vehicle */
• class Car extends Vehicle • {
•{ • Car small = new Car();
• int maxSpeed = 180;
• small.display();
• void display()
• { • }
• /* print maxSpeed of base class (vehicle) */ •}
• System.out.println("Maximum Speed: " + super.maxSpeed);
• }
• both base class and subclass have a member
•} maxSpeed. We could access maxSpeed of
• base class in sublcass using super keyword.
2. Use of super with methods: This is used when we
want to call parent class method. So whenever a parent
and child class have same named methods then to
resolve ambiguity we use super keyword. This code
snippet helps to understand the said usage of super
keyword.
• class Person • void display()
• { • {
• void message() • // will invoke or call current class message() method
• { • message();
• System.out.println("This is person class"); • // will invoke or call parent class message() method
• } • super.message();
• } • }
• /* Subclass Student */ • }
• class Student extends Person • class Test
• { • {
• void message() • public static void main(String args[])
• { • {
• System.out.println("This is student class"); • Student s = new Student();
• } • // calling display() of Student
• /* Base class Person */ • s.display();
• // Note that display() is only in Student class • }
• }
3. Use of super with constructors: super keyword can also be
used to access the parent class constructor. One more important
thing is that, ‘’super’ can call both parametric as well as non
parametric constructors depending upon the situation. Following is
the code snippet to explain the above concept:
• class Person • /* Driver program to test*/
• { • class Test
• Person() • {
• { • public static void main(String[] args)
• System.out.println("Person class Constructor"); • {
• } • Student s = new Student();
• } • }
• /* subclass Student extending the Person class */ • }
• class Student extends Person
• {
• Student()
• {
• // invoke or call parent class constructor
• super();
• System.out.println("Student class Constructor");
• }
• }
Private Access Modifier - Private
• Methods, variables, and constructors that are declared private can
only be accessed within the declared class itself.
• Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.
• Variables that are declared private can be accessed outside the class,
if public getter methods are present in the class.
• Using the private modifier is the main way that an object
encapsulates itself and hides data from the outside world.
• public class Logger {
• private String format;

• public String getFormat() {


• return this.format;
• }

• public void setFormat(String format) {


• this.format = format;
• }
•}
Public Access Modifier - Public
• A class, method, constructor, interface, • public static void main(String[]
etc. declared public can be accessed arguments) {
from any other class. Therefore, fields,
methods, blocks declared inside a public • // ...
class can be accessed from any class
belonging to the Java Universe. •}
• However, if the public class we are
trying to access is in a different package,
then the public class still needs to be
imported. Because of class inheritance,
all public methods and variables of a
class are inherited by its subclasses.
Protected Access Modifier -
Protected
• Variables, methods, and constructors, which are • class AudioPlayer {
declared protected in a superclass can be accessed only
by the subclasses in other package or any class within • protected boolean openSpeaker(Speaker sp)
the package of the protected members' class. {
• The protected access modifier cannot be applied to • // implementation details
class and interfaces. Methods, fields can be declared
protected, however methods and fields in a interface • }
cannot be declared protected. •}
• Protected access gives the subclass a chance to use the
helper method or variable, while preventing a
nonrelated class from trying to use it. • class StreamingAudioPlayer {
• Here, if we define openSpeaker() method as private,
then it would not be accessible from any other class
• boolean openSpeaker(Speaker sp) {
other than AudioPlayer. If we define it as public, then it • // implementation details
would become accessible to all the outside world. But
our intention is to expose this method to its subclass • }
only, that’s why we have used protected modifier. •}
Final – used to restrict
• Java final variable
• If you make any variable as final, you cannot change
the value of final variable(It will be constant).
• class Bike9{  
•  final int speedlimit=90;//final variable  
•  void run(){  
•   speedlimit=400;  
•  }  
•  public static void main(String args[]){  
•  Bike9 obj=new  Bike9();  
•  obj.run();  
•  }  
Java final method
• If you make any • class Bike{  
•   final void run(){System.out.println("running");}  

method as final, you • }  


•      
cannot override it • class Honda extends Bike{  
•    void run()
{System.out.println("running safely with 100kmph");}
  
•      
•    public static void main(String args[]){  
•    Honda honda= new Honda();  
•    honda.run();  
•    }  
• }  
Java final class
• If you make any class as final, • final class Bike{}  
you cannot extend it. • class Honda1 extends Bike{  
•   void run()
{System.out.println("running safely wit
h 100kmph");}  
•   public static void main(String args[]){  
•   Honda1 honda= new Honda1();  
•   honda.run();  
•   }  
• }  
Abstract class
• A class that is declared using • Lets say we have a class Animal
“abstract” keyword is known as that has a method sound() and
abstract class. It can have the subclasses(see inheritance)
abstract methods(methods of it like Dog, Lion, Horse, Cat
without body) as well as concrete etc. Since the animal sound
methods (regular methods with differs from one animal to
body). A normal class(non- another, there is no point to
abstract class) cannot have implement this method in
abstract methods parent class.
• No object can be created for
abstract class
Abstract Method
• A method without body (no Rules:
implementation) is known as 1. Abstract methods don’t have body,
they just have method signature as shown
abstract method. A method above.
must always be declared in an 2. If a class has an abstract method it
abstract class, or in other words should be declared abstract, the vice versa is
you can say that if a class has an not true, which means an abstract class
doesn’t need to have an abstract method
abstract method, it should be compulsory.
declared abstract as well 3. If a regular class extends an abstract
class, then the class must have to implement
all the abstract methods of abstract parent
class or it has to be declared abstract as well.
Example
• //abstract parent class • public void sound(){
• abstract class Animal{ • System.out.println("Woof");
• //abstract method • }
• public abstract void sound(); • public static void main(String
•} args[]){
• //Dog class extends Animal class • Animal obj = new Dog();
• public class Dog extends Animal{ • obj.sound();
• }
•}
Object class
• Object class is present • public class Object
in java.lang package. Every class in • Class Object is the root of the class
Java is directly or indirectly derived hierarchy. Every class has Object
from the Object class. If a Class does as a superclass. All objects,
not extend any other class then it is including arrays, implement the
direct child class of Object and if methods of this class.
extends other class then it is an
indirectly derived. Therefore the
Object class methods are available
to all Java classes. Hence Object
class acts as a root of inheritance
hierarchy in any Java Program.
protected Object clone()Creates and returns a copy of this object.
boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
protected void finalize()Called by the garbage collector on an object when garbage collection determines that there
are no more references to the object.

Class<?> getClass()Returns the runtime class of this Object.


int hashCode()Returns a hash code value for the object.
void notify()Wakes up a single thread that is waiting on this object's monitor.
void notifyAll()Wakes up all threads that are waiting on this object's monitor.
String toString()Returns a string representation of the object.
void wait()Causes the current thread to wait until another thread invokes the notify() method or the 
notifyAll() method for this object.

void wait(long timeout)Causes the current thread to wait until either another thread invokes the notify()
 method or the notifyAll() method for this object, or a specified amount of time has elapsed.

void wait(long timeout, int nanos)Causes the current thread to wait until another thread invokes the 
notify() method or the notifyAll() method for this object, or some other thread interrupts the current
thread, or a certain amount of real time has elapsed.
Interfaces
• An interface is a reference type in Java. It is similar to class. It is a
collection of abstract methods. A class implements an interface,
thereby inheriting the abstract methods of the interface.
• Writing an interface is similar to writing a class. But a class describes
the attributes and behaviors of an object. And an interface contains
behaviors that a class implements.
• Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
Only in java 8
• An interface is similar to a class in the following ways −
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
• However, an interface is different from a class in several ways, including −
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
• A class uses the implements keyword to • public void travel() {
implement an interface. • System.out.println("Mammal travels");
• interface Animal { • }
• public void eat(); • public int noOfLegs() {
• public void travel(); • return 0;
•} • }
• public static void main(String args[]) {
• /* File name : MammalInt.java */ • MammalInt m = new MammalInt();
• public class MammalInt implements Animal { • m.eat();
• public void eat() { • m.travel();
• System.out.println("Mammal eats"); • }
• } •}
Declaring Interface
• The interface keyword is used to • Interfaces have the following
declare an interface. properties −
• An interface is implicitly abstract.
• import java.lang.*; You do not need to use
the abstract keyword while
declaring an interface.
• public interface NameOfInterface {
• Each method in an interface is also
• // Any number of final, static fields implicitly abstract, so the abstract
• // Any number of abstract method keyword is not needed.
declarations\ • Methods in an interface are
•} implicitly public.
Extending Interfaces
• An interface can extend another interface • // Filename: Football.java
in the same way that a class can extend • public interface Football extends Sports {
another class. The extends keyword is used • public void homeTeamScored(int points);
to extend an interface, and the child • public void visitingTeamScored(int points);
interface inherits the methods of the • public void endOfQuarter(int quarter);
parent interface.
•}
• // Filename: Hockey.java
• // Filename: Sports.java • public interface Hockey extends Sports {
• public interface Sports { • public void homeGoalScored();
• public void setHomeTeam(String name); • public void visitingGoalScored();
• public void endOfPeriod(int period);
• public void setVisitingTeam(String name);
• public void overtimePeriod(int ot);
•} •}
Maker Interface
• t is an empty interface (no field or methods). Examples of marker
interface are Serializable, Clonnable and Remote interface. All these
interfaces are empty interfaces.
• Cloneable interface : Cloneable interface is present in java.lang
package. There is a method clone() in Object class. A class that
implements the Cloneable interface indicates that it is legal for clone()
method to make a field-for-field copy of instances of that class.
Invoking Object’s clone method on an instance of the class that does
not implement the Cloneable interface results in an exception
CloneNotSupportedException being thrown. By convention, classes that
implement this interface should override Object.clone() method.
• // By implementing Cloneable interface • throws CloneNotSupportedException
• // we make sure that instances of class A • {
• return super.clone();
• // can be cloned.
• }
• class A implements Cloneable
•}
•{ • public class Test
• int i; •{
• String s; • public static void main(String[] args)
• // A class constructor • throws CloneNotSupportedException
• public A(int i,String s) • {
• { • A a = new A(20, “Input");
• // cloning 'a' and holding
• this.i = i;
• // new cloned object reference in b
• this.s = s;
• // down-casting as clone() return type is Object
• } • A b = (A)a.clone();
• // Overriding clone() method • System.out.println(b.i);
• // by simply calling Object class • System.out.println(b.s);
• // clone() method. • }
• protected Object clone() •}
Serializable interface
• Serializable interface : Serializable interface is present in java.io
package. It is used to make an object eligible for saving its state into a
file. This is called Serialization.
Classes that do not implement this interface will not have any of their
state serialized or deserialized. All subtypes of a serializable class are
themselves serializable.
Remote interface 
• Remote interface : Remote interface is present in java.rmi package. A
remote object is an object which is stored at one machine and
accessed from another machine. So, to make an object a remote
object, we need to flag it with Remote interface. Here, Remote
interface serves to identify interfaces whose methods may be invoked
from a non-local virtual machine.Any object that is a remote object
must directly or indirectly implement this interface. RMI (
Remote Method Invocation) provides some convenience classes that
remote object implementations can extend which facilitate remote
object creation.

Das könnte Ihnen auch gefallen