CSE 215lab - 8
CSE 215lab - 8
CSE 215lab - 8
Inheritance is the process where one class acquires the properties (methods and fields) of another
class.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
Inheritance has two purposes - reuse existing code, reduce code duplication. When common
traits are found among two classes, define one as general/base/parent class and the other as
specific/child class. Child class inherits the properties of parent class and adds its own properties.
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Let’s see some KEYWORDS
static keyword
The static keyword belongs to the class than an instance of the class.
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
*** In Java accessors are used to get the value of a private field and mutators are used
to set the value of a private field. Accessors are also known as getters and mutators are also
known as setters***
2.
Import java.util.Date;
public class GeometricObject
{
private String color = "White"; //setting white as default color
private boolean filled;
private Date dateCreated;
public GeometricObject()
{
dateCreated = new Date();
}
public GeometricObject(String color, boolean filled)
{
this.color = color; // “this” refers to the current object
this.filled = filled;
dateCreated = new Date();
}
public String getColor()
{
return color;
}
public void setColor(String color)
{
this.color = color;
}
public boolean getFilled()
{
return filled;
}
public void setFilled(boolean filled)
{
this.filled = filled;
}
public Date getDateCreated()
{
return dateCreated;
}
public String toString()
{
return "Created on: "+dateCreated+" Color: "+color+" Filled: "+filled;
}
}
4.