类的继承

1  子类的继承(在同一包中)

class Father
{
 private int money;
 float weight,height;
 String head;
 void speak(String s)
 {
  System.out.println(s);
 }
}
class Son extends Father
{
 String hand,foot;
 
}
public class Example4_15
{
 public static void main(String args[])
 {
  Son boy;
  boy = new Son();
  boy.weight=1.80f;
  boy.height=120f;
  boy.head="一个头";
  boy.hand="两只手";
  boy.foot="两只脚";
  boy.speak("我是儿子");
  System.out.println(boy.hand + boy.foot + boy.weight + boy.height);
 }
}

 2   成员变量的隐藏和方法的重写

class Chengji
{
 float f(float x,float y)
 {
  return x*y;
 }
}
class Xiangjia extends Chengji
{
 float f(float x,float y)
 {
  return x+y;
 }
}
public class Example4_16
{
 public static void main(String args[])
 {
  Xiangjia sum;
  sum = new Xiangjia();
  float c = sum.f(4,6);
  System.out.println(c);
 }
}

注: 重写父类方法时,不可以降低方法的访问权限.

3  .   final关键字

class A
{
 //final double PI; //非法,没有给初值
 final double PI = 3.1415926; //PI是常量,给定初值
 public double getArea(final double r)
 {
  //r = 89; //非法,不允许改变r的值
  return PI*r*r;
 }
}
public class Example4_18
{
 public static void main(String args[])
 {
  A a = new A();
  System.out.println("面积是:"+a.getArea(100));
 }
}

你可能感兴趣的:(Java,float,class,string,c)